const express = require('express')
const cors = require('cors')
const mysql = require('mysql2')
const crypto = require('crypto')
const cheerio = require('cheerio')
const axios = require('axios')
const { count, table } = require('console')
const { compileFunction } = require('vm')

const app = express();

let keys = [];
const port = 8484;
const subjects = {
    '1': '物理',
    '2': '化学',
    '3': '生物',
    '4': '政治',
    '5': '历史',
    '6': '地理'
}

let tagMaskWord = [
    '科学', '技术', '学', '项目', '实验', '学术', '市场', '现代', '管理', '校企', '合作', '应用', '广告', '技术', '合作', '集团', '公司', '中外', '办学', '素质', '设备', '跨境', '师范', '工程'
]
let yuwen = [
    "语言文学",
    "汉语言文学",
    "对外汉语",
    "中国语言文学",
    "口译与翻译",
    "翻译专业",
    "文化研究",
    "文学教育",
    "文化遗产与博物馆学",
    "编辑出版学",
    "写作与创作",
    "文学批评",
    "语言学",
    "文化翻译",
    "教育教学",
    "比较文学",
    "现代文学",
    "古代文学",
    "文学思潮",
    "文艺评论",
    "教育行政",
    "写作技巧",
    "文本分析",
    "广告文案",
    "媒体伦理",
    "新闻报道",
    "媒体传媒",
    "演讲技巧",
    "外语学习",
    "社会心理学",
    "科学研究",
    "艺术表达",
    "历史研究",
    "国际关系",
    "法律行业",
    "商务领域",
    "传统文化",
    "商业沟通",
    "政府机构",
    "图书出版",
    "电影制作",
    "文化节庆",
    "社交媒体",
    "国际交流",
    "市场营销",
    "人力资源",
    "教育咨询"
]
let shuxue = [
    "数学",
    "车辆工程",
    "应用数学",
    "统计学",
    "金融数学",
    "运筹学",
    "数学建模",
    "数理金融",
    "数量经济学",
    "金融工程",
    "微积分",
    "线性代数",
    "概率论",
    "数值分析",
    "图论",
    "数学模型",
    "数论",
    "函数论",
    "离散数学",
    "数学物理",
    "动力系统",
    "数据科学",
    "人工智能",
    "机器学习",
    "深度学习",
    "云计算",
    "大数据",
    "数据隐私",
    "量子计算",
    "数字货币",
    "加密算法",
    "区块链技术",
    "数据挖掘",
    "电子商务",
    "金融市场",
    "算法设计",
    "网络安全",
    "程序开发",
    "通信工程",
    "供应链管理",
    "健康统计",
    "环境统计",
    "工程技术领域",
    "医学研究",
    "教育研究",
    "经济分析",
    "数据治理",
    "金融机构",
    "投资银行",
    "制造业",
    "电子商务企业",
    "科技公司",
    "医疗健康行业",
    "能源领域",
    "市场研究",
    "物流管理",
    "决策分析",
    "人力资源管理",
    "品牌管理",
    "项目管理"
]
let waiyu = [
    "外语",
    "英语语言文学",
    "日语语言文学",
    "法语语言文学",
    "德语语言文学",
    "俄语语言文学",
    "西班牙语语言文学",
    "意大利语语言文学",
    "对外汉语",
    "翻译专业",
    "翻译与口译",
    "语言学",
    "对外汉语教育",
    "国际商务英语",
    "外贸英语",
    "旅游英语",
    "外语教育",
    "语言测试与评估",
    "外语资源开发与管理",
    "文化研究",
    "跨文化交流",
    "跨文化传媒",
    "外国文学",
    "跨文化管理",
    "外语口译",
    "外语翻译",
    "外语教学",
    "国际关系",
    "公共外交",
    "国际事务",
    "教育行政管理",
    "外语编辑",
    "外语出版",
    "外语咨询",
    "外语评估",
    "翻译服务",
    "社会热点",
    "一带一路倡议",
    "双语教育",
    "网络翻译",
    "科技翻译",
    "文化交流",
    "学科竞赛",
    "留学申请",
    "国际合作项目",
    "文化活动策划",
    "翻译公司",
    "跨国企业",
    "外贸公司",
    "虚拟交流",
    "自主学习",
    "文化遗产保护",
    "环境保护",
    "媒体传媒",
    "国际组织",
    "外交部门",
    "旅游业",
    "酒店管理",
    "航空公司",
    "国际企业",
    "跨文化咨询",
    "跨文化培训",
    "商务沟通",
    "市场调研",
    "国际市场营销",
    "法律事务",
    "艺术领域",
    "文化创意",
    "教育研究",
    "计算机科学",
    "互联网技术",
    "电子商务",
    "市场营销",
    "人力资源",
    "国际金融",
    "国际贸易",
    "旅游管理",
    "人文科学",
    "社会科学",
    "文化产业",
    "国际关系",
    "国际交流"
]
let wuli = ["物理学", "力学与弹性", "光学与光电子学", "天体物理学", "核物理学", "凝聚态物理学", "声学工程", "热学", "电磁学", "计算物理学", "理论物理学", "物理教育", "应用物理学", "物理化学", "生物物理学", "空间科学", "材料科学与工程", "核工程与核技术", "电力系统及自动化", "电子信息工程", "测控技术与仪器", "能源与动力工程", "环境科学与工程", "光信息科学与技术", "机械设计制造及其自动化", "机械电子工程", "机械工程及自动化", "材料成型及控制工程", "汽车服务工程", "金属材料工程", "土木工程", "建筑环境与能源应用工程", "建筑管理", "建筑学", "生物医学工程", "食品科学与工程", "安全工程", "化学工程与工艺", "环境工程", "生物工程", "水利水电工程", "交通运输工程", "信息与计算科学", "计算机科学与技术", "软件工程", "物理研究员", "工程师", "技术支持", "数据分析师", "项目经理", "教师", "科研助理", "实验室技术员", "质量控制员", "能源顾问", "天文学家", "电力工程师", "机电", "维修", "人工智能", "车辆工程"]
let huaxue = ["化学", "有机化学", "无机化学", "分析化学", "物理化学", "生物化学", "材料化学", "环境化学", "药物化学", "化学制药", "食品化学", "聚合物化学", "化学生物学", "化学物理学", "配位化学", "表面化学", "现代分析技术", "能源化学", "超分子化学", "生物无机化学", "纳米化学", "催化化学", "波谱分析", "质谱分析", "色谱分析", "电化学", "化学教师", "化学工程师", "实验室技术员", "化学研究员", "药物研发科学家", "化学分析师", "化妆品研发工程师", "环境工程师", "材料科学家", "化学销售代表", "化学行业顾问", "化学品质检员", "化学教育培训师", "科研助理", "化学实验员", "化学生产经理", "化学产品技术支持", "化学品安全管理", "化学合成工艺", "化学品市场分析", "化学工程技术员", "化学原料采购", "化学废物处理", "化学装备维护", "化学仪器销售", "高分子材料", "药物研发", "化学反应", "实验室设备", "化学实验", "化学平衡", "化学方程式", "酸碱中和", "化学键", "化学性质", "化学物质", "化学反应速率", "化学平衡常数", "化学键能", "化学键长", "化学键角", "化学药品", "化学实验室", "化学浓度", "化学反应动力学", "化学平衡常数", "化学反应热力学", "化学官能团", "化学化合物", "化学元素周期表", "化学键的极性", "化学催化剂", "化学溶液", "有机合成", "无机化合物", "生物化学反应", "配位化合物", "化学分析方法", "化学仪器设备", "化学原理", "量子化学", "化学实验技巧", "化学安全操作", "化学循环经济", "环保化学", "化学废物处理技术", "绿色化学", "化学工程设计", "化学品安全", "能源储存技术", "绿色能源", "环境污染", "化学品安全", "环境保护", "塑料污染", "微塑料", "可降解塑料", "新型材料", "新药研发", "绿色合成", "可再生能源", "碳排放", "温室气体", "环境监测", "实验技术", "化学工艺", "审计学", "会计学"]
let shengwu = [
    "生物学",
    "分子生物学",
    "细胞生物学",
    "生物技术",
    "生态学",
    "遗传学",
    "生物信息学",
    "生物医学工程",
    "生物工程",
    "生物化学",
    "植物学",
    "动物学",
    "微生物学",
    "生态学",
    "环境科学",
    "生物医学科学",
    "生物教育",
    "遗传工程",
    "生物化学工程",
    "生物信息工程",
    "生物科学教育",
    "生物技术管理",
    "生物医学研究",
    "生物药物研发",
    "病理学",
    "基因组学",
    "蛋白质组学",
    "表观遗传学",
    "系统生物学",
    "生物样本管理",
    "疫苗研发",
    "基因工程",
    "基因组编辑",
    "转基因技术",
    "生物制药",
    "食品科学",
    "农业科学",
    "野生动物保护",
    "自然保护",
    "生物多样性保护",
    "生态系统保护",
    "动物行为学",
    "植物生理学",
    "微生物生态学",
    "生态系统模拟",
    "种子库管理",
    "生物安全",
    "生物伦理",
    "遗传咨询",
    "科学研究",
    "实验室技术",
    "数据分析",
    "科研助理",
    "科研项目",
    "科学实验",
    "生物测量学",
    "基因测序",
    "细胞培养",
    "动物实验",
    "植物培养",
    "基因分析",
    "细胞分析",
    "分子克隆",
    "PCR技术",
    "生物芯片",
    "蛋白质鉴定",
    "生物样本采集",
    "生物标本处理",
    "生物统计学",
    "生物化学",
    "医学研究",
    "环境科学",
    "农业科学",
    "神经科学",
    "营养学",
    "药学",
    "计算机科学",
    "数据科学",
    "工程学",
    "环境工程",
    "生物工程",
    "农业工程",
    "基因治疗",
    "人工智能",
    "虚拟现实",
    "可持续发展",
    "气候变化",
    "生物技术产业",
    "天然资源保护",
    "新药开发",
    "食品安全",
    "临床研究",
    "生物能源",
    "植物育种",
    "疾病治疗",
    "遗传咨询",
    "转基因作物",
    "农业生产",
    "生物医学设备",
    "药物生产",
    "医疗保健",
    "大众健康",
    "食品加工",
    "环境保护",
    "生物科技创业",
    "科学教育",
    "自然科学研究",
    "环境管理",
    "医药销售",
    "市场营销"
]
let zhengzhi = [
    "政治学",
    "国际关系",
    "公共管理",
    "公共政策",
    "政府管理",
    "行政管理",
    "政治理论",
    "政治经济学",
    "比较政治",
    "政治心理学",
    "政治传媒",
    "政治社会学",
    "政治教育",
    "政治哲学",
    "政治史学",
    "政治研究",
    "公共事务",
    "国际事务",
    "外交关系",
    "政治顾问",
    "政治分析师",
    "政治记者",
    "政府部门",
    "公共机构",
    "法律事务",
    "政治咨询",
    "政治沟通",
    "政治策划",
    "政治组织",
    "政治运动",
    "政治活动",
    "选举与投票",
    "政府管理",
    "社会政策",
    "公共服务",
    "社会福利",
    "公共安全",
    "公共卫生",
    "教育行政",
    "政府宣传",
    "政治决策",
    "志愿填报",
    "研究方向",
    "学术交流",
    "学科竞赛",
    "政治实践",
    "政治论文",
    "政治课程",
    "政治理论",
    "政治思潮",
    "政治制度",
    "政治稳定",
    "公民权利",
    "社会公正",
    "政党制度",
    "政治权力",
    "政治改革",
    "政治体制",
    "社会热点",
    "政治领导力",
    "危机管理",
    "民主和专制",
    "社会运动",
    "恐怖主义",
    "军事冲突",
    "地区冲突",
    "国际合作",
    "公民参与",
    "社会不平等",
    "公共政策分析",
    "市场调研",
    "政治经济学",
    "政治体制改革",
    "国际政治经济学",
    "人权与社会正义",
    "政治营销",
    "政治传播",
    "政治风险评估",
    "政治与社会发展",
    "决策分析",
    "政策评估",
    "公共财政管理",
    "政治决策流程",
    "公民教育",
    "社会研究方法",
    "国际关系理论",
    "政治与环境",
    "城市政策规划",
    "社会调查研究",
    "市场营销研究",
    "公共关系管理",
    "人力资源管理",
    "公共危机管理",
    "政治战略",
    "新闻报道与分析",
    "市场咨询",
    "研究咨询",
    "政府咨询",
    "政治风险分析",
    "国际经济合作",
    "社会企业",
    "社会创新",
    "社会心理咨询",
    "国际援助",
    "公共卫生管理"
]
let lishi = [
    "历史学",
    "考古学",
    "文物鉴赏与保护",
    "文化遗产学",
    "博物馆学",
    "古代文明研究",
    "文化传播与管理",
    "民族学",
    "人类学",
    "历史研究员",
    "考古学家",
    "博物馆馆长",
    "文物保护员",
    "文化遗产管理师",
    "教师",
    "研究助理",
    "文化传媒从业者",
    "历史解读员",
    "文化艺术顾问",
    "历史事件",
    "文明发展",
    "政治制度",
    "社会变革",
    "文化交流",
    "战争",
    "革命",
    "古代文物",
    "考古发现",
    "文化保护",
    "历史遗址",
    "博物馆藏品",
    "人类演化",
    "化石记录",
    "社会文化",
    "民族文化",
    "史料研究",
    "口述历史",
    "思想流派",
    "教育"
]
let dili = [
    "地理学",
    "自然地理与资源环境",
    "人文地理与城乡规划",
    "地理信息科学",
    "地理信息系统",
    "海洋地质学",
    "气候学",
    "生态学",
    "地球科学",
    "地理信息系统工程师",
    "城市规划师",
    "环境保护专员",
    "地理学教师",
    "地质勘探工程师",
    "气候研究员",
    "生态保护员",
    "资源管理专员",
    "旅游规划师",
    "地理数据分析师",
    "地形地貌",
    "自然灾害",
    "水资源",
    "气候变化",
    "生物多样性",
    "城市化",
    "人口迁移",
    "城市规划",
    "经济地理",
    "农业发展",
    "交通网络",
    "区域规划",
    "水文循环",
    "地理坐标",
    "地球板块",
    "地壳运动",
    "地貌演化",
    "生态系统",
    "地图制作",
    "地理调查",
    "野外探索",
    "研究项目",
    "地理数据分析",
    "实地考察",
    "地理模拟",
]

process.env.NODE_TLS_REJECT_UNAUTHORIZED = false;

app.use(cors())
// const db = mysql.createPool({
//     host:'127.0.0.1',
//     user:'root',
//     password:'root',
//     database:'ceevidms',
//     // port:3306
// })
const db = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: 'Catiouszty2004_',
    database: 'ktzx',
    // port:3306
})

/////////////////////////////////////////////
//志愿助手

app.post('/api/v1/expcard/changeStatus', (req, res) => {
    try {
        const data = JSON.parse(req.query.data)
        db.query("update expcard set used = 1 where keyString = '" + data.keyString + "'", (err, result) => {
            res.send({
                status: 1,
                content: '查询成功',
                results: result
            })
        })
    } catch (error) {
        res.send({
            status: 0,
            content: '修改失败'
        })
    }
})

app.get('/api/v1/expcard/status', (req, res) => {
    try {
        const data = JSON.parse(req.query.data)
        db.query("select * from expcard where keyString = '" + data.keyString + "'", (err, result) => {
            res.send({
                status: 1,
                content: '查询成功',
                results: result
            })
        })
    } catch (error) {
        res.send({
            status: 0,
            content: '查询失败'
        })
    }
})

app.post('/api/v1/expcard/generate', async (req, res, next) => {
    // try{
    const form = JSON.parse(req.query.data)
    db.query("select * from scoreranking where year = " + subtractYear(1) + " order by ranking", async (err, result) => {
        let flag = false
        for (let i = 0; i < result.length; i++) {
            if (form.ranking <= result[i].ranking1) {
                form['score'] = result[i].score1
                flag = true
                break
            }
        }
        if (flag == false) {
            form['score'] = result[result.length - 1].score1
        }
        form.rankMethod = true


        // if(form.score > 730 || form.score < 220 ) //判断分数是否在十分以内
        //     form.rankMethod = false

        // 默认位次法
        form.year = 2022
        form.page = -1
        const addSql = conditionSql(form)
        let aplications;
        form.scoreUp = 10
        form.scoreDown = 20

        if (form.rankMethod)
            aplications = await rankMethod(form, addSql);
        else
            aplications = await lineDifMethod(form, addSql);


        aplications = removeSMSR(aplications, form)



        aplications = fff(aplications, form)

        sortAppl(aplications.chong)
        sortAppl(aplications.bao)
        sortAppl(aplications.wen)


        const arr = []



        let temp;
        if (aplications.chong.length > 16) {
            temp = parseInt(aplications.chong.length / 16)
            for (let i = 0; i < aplications.chong.length - temp; i += temp) {
                arr.push(aplications.chong[i])
            }
        } else
            arr.push(...aplications.chong)
        if (aplications.wen.length > 48) {

            temp = parseInt(aplications.wen.length / 48)
            for (let i = 0; i < aplications.wen.length - temp; i += temp) {
                arr.push(aplications.wen[i])
            }
        } else arr.push(...aplications.wen)
        if (aplications.bao.length > 32) {

            temp = parseInt(aplications.bao.length / 32)
            for (let i = 0; i < aplications.bao.length - temp; i += temp) {
                if (arr.length >= 96)
                    break
                arr.push(aplications.bao[i])
            }
        } else arr.push(...aplications.bao)
        aplications = arr
        let formName = '智能填报' + generateTimeString();



        let sqls = []
        let re = []
        aplications.forEach((item, i) => {
            sqls[i] = `('${form.keyString}','${item.majorName}','${item.majorCode}','${item.universityName}','${item.universityCode}',${i + 1})`
            re[i] = [i + 1, item.majorCode, item.majorName, item.universityCode, item.universityName]
        })
        const sql = `insert into expcardresults(keyString,majorName,majorCode,universityName,universityCode,index0) values${sqls.join(',')}`

        db.query(sql, (err, result) => {
            if (err) {
                return res.send({
                    msg: '填报错误'
                })
            }
            db.query("update expcard set used = 1, detail = " + JSON.stringify(form) + " where keyString = '" + form.keyString + "'", (err1, results4) => {
                if (err1) {
                    return res.send({
                        msg: '填报错误'
                    })
                } else {
                    return res.send({
                        content: '填报成功',
                        status: 1,
                        results: re
                    })
                }
            })
        })
    })
    // } catch (err) {
    //     // 将错误传递给错误处理中间件
    //     next(err);
    // }
})

app.get('/api/v1/expcard/getAll', (req, res) => {
    try {
        const data = JSON.parse(req.query.data)
        db.query("select * from expcard where keyString like '%" + data.keyString + "%' and used like '%" + (data.used == '不限' ? '' : (data.used == '未使用' ? 0 : (data.used == '已使用一次' ? 1 : 2))) + "%'", (err, results) => {
            res.send({
                status: 1,
                content: '获取成功',
                results: results
            })
        })
    } catch (error) {
        res.send({
            status: 0,
            content: '获取失败'
        })
    }
})

app.post('/api/v1/expcard/add', (req, res) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            if (isJSONString(formData)) {
                let data = JSON.parse(formData)
                data = data.split(',')
                if (data[0] == '' && data.length == 1) {
                    res.send({
                        status: 0,
                        content: '请输入序列号'
                    })
                    return
                }
                let count = 0
                for (let i = 0; i < data.length; i++) {
                    db.query("insert into expcard values('" + data[i] + "',0,'')", (err, results) => {
                        count++
                        if (count == data.length) {
                            res.send({
                                status: 1,
                                content: '导入成功'
                            })
                        }
                    })
                }
            } else {
                res.send({
                    status: 0,
                    content: '导入失败，请尝试重新导入'
                })
            }
        })
    } catch (error) {
        res.send({
            status: 0,
            content: '导入失败，请尝试重新导入'
        })
    }
})

/////////////////////////////////////////////

let userStatus = [];

let unreadNums = [];

app.post("/api/v1/user/changePassword", (req, res) => {
    try {
        const data = JSON.parse(req.query.data)
        db.query("select * from users where account = '" + data.account + "'", (err, results) => {
            if (err) {
                console.log(err)
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                if (results[0].password != data.op) {
                    res.send({
                        status: 0,
                        content: '原密码错误，修改失败'
                    })
                } else {
                    db.query("update users set password = '" + data.np + "' where account = '" + data.account + "'", (err, results1) => {
                        if (err) {
                            console.log(err)
                            res.send({
                                status: 0,
                                content: '修改失败'
                            })
                        } else {
                            res.send({
                                status: 1,
                                content: '修改成功'
                            })
                        }
                    })
                }
            }
        })
    } catch (error) {
        res.send({
            status: 0,
            content: '修改失败'
        })
    }

})

app.post("/api/v1/record/add", (req, res) => {
    db.query("insert into accessrecord values('" + formatCurrentTime() + "')");
    res.send({
        status: 1,
        content: '成功'
    })
})

app.get('', (req, res) => {
    res.send('您已成功连接高考志愿智能决策系统后端！')
})

app.post('/api/v1/universities/onlineRefresh', (req, res) => {
    axios.get("https://static-data.gaokao.cn/www/2.0/info/linkage.json").then(res2 => {
        const schools = res2.data.data.school
        let datas = []
        let count = 0
        for (let i = 0; i < schools.length; i++) {
            axios.get("https://static-data.gaokao.cn/www/2.0/school/" + schools[i].school_id + "/info.json").then(res1 => {
                let getted = res1.data.data
                datas.push({
                    name: getted.name,
                    remark: getted.data_code,
                    department: getted.belong,
                    province: getted.province_name,
                    city: getted.city_name,
                    level: getted.level_name.slice(2, 4),
                    focus: (getted.f985 == '1' ? '985 ' : '') + (getted.f211 == '1' ? '211' : ''),
                    firstRate: getted.dual_class_name,
                    type: getted.type_name,
                    year: '',
                    yearCount: getted.create_date,
                    public: getted.school_nature_name,
                    subject1: '',
                    subject2: '',
                    minScore: 0,
                    minRanking: 0
                })
                count += 1
                if (count == schools.length) {
                    db.query("delete from universities", (err, results) => {
                        let count1 = 0
                        for (let i1 = 0; i1 < datas.length; i1++) {
                            let string = ''
                            let isFirst = true
                            for (let i2 = 0; i2 < Object.keys(datas[i1]).length; i2++) {
                                if (isFirst) {
                                    isFirst = false
                                } else {
                                    string += ','
                                }
                                if (Object.keys(datas[i1])[i2] != 'minScore' && Object.keys(datas[i1])[i2] != 'minRanking') {
                                    string += "'"
                                }
                                string += datas[i1][Object.keys(datas[i1])[i2]]
                                if (Object.keys(datas[i1])[i2] != 'minScore' && Object.keys(datas[i1])[i2] != 'minRanking') {
                                    string += "'"
                                }
                            }
                            db.query("insert into universities values(" + string + ")", (err, results1) => {
                                if (err) {
                                    console.log(err)
                                }
                                count1 += 1
                                if (count1 == datas.length) {
                                    res.send({
                                        status: 1,
                                        content: '更新成功'
                                    })
                                }
                            })
                        }
                    })
                }
            })
        }
    })
})

app.post("/api/v1/qa/delete", (req, res) => {


    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from qa where account = '" + data.account + "' and content = '" + data.content + "' and toAccount = '" + data.toAccount + "' and time = '" + data.time + "'", (err, results) => {
            if (err) {
                console.log(err)
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '删除成功'
                })
            }
        })
    } catch (err) {

        next(err)

    }

})

app.get("/api/v1/qa/listMy", (req, res) => {


    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from qa where account = '" + data.account + "'", (err, results) => {
            if (err) {
                console.log(err)
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                let temp1 = [];
                for (let i = results.length - 1; i >= 0; i--) {
                    temp1.push(results[i]);
                }
                const total = temp1.length;
                let count = 0;
                if (total == 0) {
                    res.send({
                        status: 1,
                        content: '获取成功',
                        results: []
                    })
                    return;
                }
                for (let i = 0; i < total; i++) {
                    db.query("select * from users where account = '" + temp1[i].account + "'", (err, results1) => {
                        count += 1;
                        if (results1.length == 0) {
                            temp1[i]['userInfo'] = undefined;
                        } else {
                            temp1[i]['userInfo'] = results1[0];
                        }
                        if (count == total) {
                            let temp2 = [];
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].userInfo != undefined) {
                                    temp2.push(temp1[i1]);
                                    temp2[temp2.length - 1]['a'] = [];
                                }
                            }
                            let temp3 = [];
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].toAccount == '-') {
                                    for (let i2 = temp1.length - 1; i2 >= 0; i2--) {
                                        if (temp1[i2].toAccount == (temp1[i1].account + temp1[i1].time)) {
                                            temp1[i1].a.push(temp1[i2]);
                                        }
                                    }
                                }
                            }
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].toAccount == '-') {
                                    temp3.push(temp1[i1]);
                                }
                            }
                            res.send({
                                status: 1,
                                content: '获取成功',
                                results: temp3
                            })
                            return;
                        }
                    })
                }
            }
        })
    } catch (err) {

        next(err)

    }

})

app.get("/api/v1/qa/listAll", (req, res) => {



    try {
        db.query("select * from qa", (err, results) => {
            if (err) {
                console.log(err)
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                let temp1 = [];
                for (let i = results.length - 1; i >= 0; i--) {
                    temp1.push(results[i]);
                }
                const total = temp1.length;
                let count = 0;
                if (total == 0) {
                    res.send({
                        status: 1,
                        content: '获取成功',
                        results: []
                    })
                    return;
                }
                for (let i = 0; i < total; i++) {
                    db.query("select * from users where account = '" + temp1[i].account + "'", (err, results1) => {
                        count += 1;
                        if (results1.length == 0) {
                            temp1[i]['userInfo'] = undefined;
                        } else {
                            temp1[i]['userInfo'] = results1[0];
                        }
                        if (count == total) {
                            let temp2 = [];
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].userInfo != undefined) {
                                    temp2.push(temp1[i1]);
                                    temp2[temp2.length - 1]['a'] = [];
                                }
                            }
                            let temp3 = [];
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].toAccount == '-') {
                                    for (let i2 = temp1.length - 1; i2 >= 0; i2--) {
                                        if (temp1[i2].toAccount == (temp1[i1].account + temp1[i1].time)) {
                                            temp1[i1].a.push(temp1[i2]);
                                        }
                                    }
                                }
                            }
                            for (let i1 = 0; i1 < temp1.length; i1++) {
                                if (temp1[i1].toAccount == '-') {
                                    temp3.push(temp1[i1]);
                                }
                            }
                            res.send({
                                status: 1,
                                content: '获取成功',
                                results: temp3
                            })
                            return;
                        }
                    })
                }
            }
        })
    } catch (err) {

        next(err)

    }

})

app.post("/api/v1/qa/add", (req, res) => {

    try {
        req.on('data', data => {
            let formData = decodeURIComponent(data)
            const predata = JSON.parse(formData)
            db.query("insert into qa values('" + predata.account + "','" + predata.content + "','" + formatCurrentTime() + "','" + predata.toAccount + "')", (err, results) => {
                if (err) {
                    console.log(err)
                    res.send({
                        status: 0,
                        content: '发表失败'
                    })
                } else {
                    res.send({
                        status: 1,
                        content: "发表成功"
                    })
                }
            })
        })
    } catch (err) {

        next(err)

    }


})

function fff(aplications, form) {
    const res = {
        chong: [],
        bao: [],
        wen: []
    }
    for (let i = 0; i < aplications.length; i++) {
        if (aplications[i].ranking3 < form.ranking && aplications[i].ranking2 < form.ranking && aplications[i].ranking1 < form.ranking) {
            res.chong.push(aplications[i])
            continue
        }
        if (aplications[i].ranking3 > form.ranking && aplications[i].ranking2 > form.ranking && aplications[i].ranking1 > form.ranking) {
            res.bao.push(aplications[i])
            continue
        }
        else {
            res.wen.push(aplications[i])
            continue

        }

    }
    return res

}
// app.get("/api/v1/getAllPage")

app.get("/api/v1/vip/smartSearch", async (req, res, next) => {
    try {
        // 抛出一个错误
        const form = JSON.parse(req.query.data)
        // if(<form.score+form.scoreUp ) 判断分数是否在十分以内 

        form.rankMethod = true // 默认位次法
        form.year = 2022
        form.page = -1
        const addSql = conditionSql(form)
        let aplications;
        // form.scoreUp = 4
        // form.scoreDown = 5
        if (form.rankMethod)
            aplications = await rankMethod(form, addSql);
        else
            aplications = await lineDifMethod(form, addSql);

        // if(form.isSM == 1 || form.isSR == 1)
        //     aplications = removeSMSR(aplications)

        addDisabled(aplications, form)



        aplications = fff(aplications, form)

        sortAppl(aplications.bao)
        sortAppl(aplications.chong)
        sortAppl(aplications.wen)




        res.send({
            chong: aplications.chong.slice(aplications.chong.length - 10 * (form.chongL) < 0 ? 0 : aplications.chong.length - 10 * (form.chongL), aplications.chong.length - 10 * (form.chongL - 1)).reverse(),
            wen: aplications.wen.slice(10 * (form.wenL - 1), 10 * (form.wenL) > aplications.wen.length ? aplications.wen.length : 10 * (form.wenL)),
            bao: aplications.bao.slice(10 * (form.baoL - 1), 10 * (form.baoL) > aplications.bao.length ? aplications.bao.length : 10 * (form.baoL)),
            chongL: Math.ceil(aplications.chong.length / 10),
            wenL: Math.ceil(aplications.wen.length / 10),
            baoL: Math.ceil(aplications.bao.length / 10),

        })


    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }


})

function removeSMSR(aplications, form) {
    const res = []
    const okSubs = getOkSubs(form.subjects)
    let has = false
    if (form.isSR || form.isSM) has = true
    aplications.forEach((el, i) => {
        if (has && (form.isSM == 1 && el.majorName.indexOf("色盲") != -1 || form.isSR == 1 && el.majorName.indexOf("色弱") != -1)) {
            el.enabled = false
        } else
            el.enabled = true
        el.enabled = el.enabled && isOkSub(el.subject, okSubs)
        if (el.enabled) {
            res.push(el)
        }
    })
    return res
}

function sortAppl(aplications) {
    aplications.sort((a, b) => {
        let count = 0;
        if (a.ranking3 < b.ranking3) count++
        if (a.ranking2 < b.ranking2) count++
        if (a.ranking1 < b.ranking1) count++
        // 122000 4000 8000
        // 3000 10000 10000

        if (count >= 2) return -1 // 顺序不变
        return 1 // 顺序改变

    })
}

function addDisabled(aplications, form) {

    const okSubs = getOkSubs(form.subjects)
    let has = false
    if (form.isSR || form.isSM) has = true
    aplications.forEach((el, i) => {
        if (has && (form.isSM == 1 && el.majorName.indexOf("色盲") != -1 || form.isSR == 1 && el.majorName.indexOf("色弱") != -1)) {
            el.enabled = false
        } else
            el.enabled = true
        el.enabled = el.enabled && isOkSub(el.subject, okSubs)
    })

}

function isOkSub(subjectStr, okSubs) {
    if (subjectStr == '不限') return true
    if (subjectStr.indexOf('和') != -1) {
        return okSubs.he.indexOf(subjectStr) != -1
    }
    let flag = false
    okSubs.huo.forEach((el) => {
        if (subjectStr.indexOf(el) != -1) {
            flag = true
            return
        }
    })
    return flag
}

function getOkSubs(subject) {
    const arr = [subjects[subject[1]], subjects[subject[2]], subjects[subject[3]]]
    const res = {
        'huo': arr,
        'he': [`${arr[0]}和${arr[1]}`, `${arr[0]}和${arr[2]}`, `${arr[1]}和${arr[2]}`],
    }
    return res;
}

function getAllOnePointOneSegmentTables() {
    return new Promise((resolve, reject) => {
        db.query("select * from scoreranking where year = " + subtractYear(1) + " order by ranking", (err, results1) => {
            db.query("select * from scoreranking where year = " + subtractYear(2) + " order by ranking", (err, results2) => {
                db.query("select * from scoreranking where year = " + subtractYear(3) + " order by ranking", (err, results3) => {
                    return resolve({
                        year1: results1,
                        year2: results2,
                        year3: results3
                    })
                })
            })
        })
    })
}

function getScoreRange(ranking, scoreUp, scoreDown, table) {
    let score = 0
    for (let i = 0; i < table.length; i++) {
        if (table[i].ranking >= ranking) {
            score = table[i].score
            return [score - scoreDown, score + scoreUp]
        }
    }
    return [table[table.length - 1].score - scoreDown, table[table.length - 1].score + scoreUp]
}

function getRankingRangeByScoreRange(scoreRange, table) {
    let flag = 0
    let re = [-1, -1]
    for (let i = 0; i < table.length; i++) {
        if (table[i].score <= scoreRange[0] && re[0] == -1) {
            re[0] = table[i].ranking
            flag += 1
        }
        if (table[i].score <= scoreRange[1] && re[1] == -1) {
            re[1] = table[i].ranking
            flag += 1
        }
        if (flag == 2) {
            return re
        }
    }
    return re
}

function getAllTheVolunteersFromTheDatabase() {
    return new Promise((resolve, reject) => {
        db.query("select * from majors", (err, results) => {
            return resolve(results)
        })
    })
}

function compareVolunteerItem(yearSub, attributePrefixName) {
    return function (a, b) {
        if (a[attributePrefixName + yearSub.toString()] == 0) {
            return 999999
        }
        if (b[attributePrefixName + yearSub.toString()] == 0) {
            return -999999
        }
        return a[attributePrefixName + yearSub.toString()] - b[attributePrefixName + yearSub.toString()]
    }
}

function compareVolunteerItemByAllRate() {
    return function (a, b) {
        return a.rate.all - b.rate.all
    }
}

function getTheMaximumAndMinimumForAYear(allTheVolunteersInTheOrder, yearSub, attributePrefixName) {
    let re = [-1, -1]
    re[1] = allTheVolunteersInTheOrder[0][attributePrefixName + yearSub.toString()]
    for (let i = allTheVolunteersInTheOrder.length - 1; i >= 0; i--) {
        if (allTheVolunteersInTheOrder[i][attributePrefixName + yearSub.toString()] != 0) {
            re[0] = allTheVolunteersInTheOrder[i][attributePrefixName + yearSub.toString()]
            return re
        }
    }
    return re
}

function whetherStudentsChooseThisSubject(volunteerItem, form) {
    if (volunteerItem.subject == "不限") {
        return true
    }
    let subs = []
    for (let i = 1; i <= 3; i++) {
        switch (form.subjects.slice(i, i + 1)) {
            case '1':
                subs.push('物理')
                break;
            case '2':
                subs.push('化学')
                break;
            case '3':
                subs.push('生物')
                break;
            case '4':
                subs.push('政治')
                break;
            case '5':
                subs.push('历史')
                break;
            case '6':
                subs.push('地理')
                break;
        }
    }
    if (isInclude(subs, volunteerItem.subject)) {
        return true
    }
    return false
}

function whetherTheCandidatesPhysicalLimitationsMeetTheRequirements(volunteerItem, form) {
    if (volunteerItem.batch != form.batch) {
        return false
    }
    if (form.isSM == 1 && isSubstring("色盲", volunteerItem.majorName) == true) {
        return false
    }
    if (form.isSR == 1 && isSubstring("色弱", volunteerItem.majorName) == true) {
        return false
    }
    return true
}

function whetherTheVolunteerProjectIsSelected(volunteerItem, scoreRange, minimumNumberOfEntries, form) {
    if (form.provinces.length != 0) {
        let flag = false
        for (let i = 0; i < form.provinces.length; i++) {
            if (isSubstring(form.provinces[i], volunteerItem.province) == true) {
                flag = true
                break
            }
        }
        if (!flag) {
            return false
        }
    }
    if (form.majorName.length != 0) {
        let flag = false
        for (let i = 0; i < form.majorName.length; i++) {
            if (isSubstring(form.majorName[i], volunteerItem.majorName) == true) {
                flag = true
                break
            }
        }
        if (!flag) {
            return false
        }
    }
    if (form.levels.length != 0) {
        let flag = false
        for (let i = 0; i < form.levels.length; i++) {
            if (isSubstring(form.levels[i], volunteerItem.level) == true) {
                flag = true
                break
            }
        }
        if (!flag) {
            return false
        }
    }
    if (volunteerItem.money != '待定' && parseInt(volunteerItem.money) > parseInt(form.moneyMax)) {
        return false
    }
    if (form.universityName.length != 0) {
        if (isSubstring(form.universityName, volunteerItem.universityName) == false) {
            return false
        }
    }
    let count = 0
    if (volunteerItem.score1 >= scoreRange[0] && volunteerItem.score1 <= scoreRange[1]) {
        count += 1
    }
    if (volunteerItem.score2 >= scoreRange[0] && volunteerItem.score2 <= scoreRange[1]) {
        count += 1
    }
    if (volunteerItem.score3 >= scoreRange[0] && volunteerItem.score3 <= scoreRange[1]) {
        count += 1
    }
    if (count >= minimumNumberOfEntries) {
        return true
    }
    return false
}

function removeVolunteersWhoseSubjectsDoNotMatchTheirPhysicalLimitations(allVolunteerItems, form) {
    let re = []
    for (let i = 0; i < allVolunteerItems.length; i++) {
        if (whetherStudentsChooseThisSubject(allVolunteerItems[i], form) == true && whetherTheCandidatesPhysicalLimitationsMeetTheRequirements(allVolunteerItems[i], form) == true) {
            re.push(allVolunteerItems[i])
        }
    }
    return re
}

function calculateTheSingleYearAdmissionProbability(ranking, num, stuRanking, maximumAndMinimumRank, maximumAndMinimumEnrollment, sortedListOfPureAdmissions, volunteerItemsTotal, config) {
    let r1 = 0
    if (ranking == stuRanking) {
        r1 = 0.5
    } else if (ranking < stuRanking) {
        r1 = Math.pow(1 - (stuRanking - ranking) / (stuRanking - maximumAndMinimumRank[1]), 5) * 0.5
    } else {
        r1 = Math.pow((ranking - stuRanking) / (maximumAndMinimumRank[0] - stuRanking), 0.2) * 0.5 + 0.5
    }
    let r2 = 0
    for (let i = 0; i < sortedListOfPureAdmissions.length; i++) {
        if (sortedListOfPureAdmissions[i][0] == num) {
            r2 += sortedListOfPureAdmissions[i][1] / 2
            r2 = r2 / volunteerItemsTotal
            break
        }
        r2 += sortedListOfPureAdmissions[i][1]
    }
    r2 = Math.pow(r2, 0.3)
    return r1 * config.theProportionOfTheNumberOfCandidatesAndTheNumberOfAdmissionsToTheProbability[0] + r2 * config.theProportionOfTheNumberOfCandidatesAndTheNumberOfAdmissionsToTheProbability[1]
    // r1 = Math.pow(r1,0.5)
    // r2 = Math.pow(r2,0.3)
    // return r1 * r2
}

function gainAcceptanceRate(volunteerItem, form, theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears, allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears, sortedListOfPureAdmissionsOfThePreviousThreeYears, volunteerItemsTotal, config) {
    volunteerItem['rate'] = {
        year1: calculateTheSingleYearAdmissionProbability(volunteerItem.ranking1, volunteerItem.num1, form.ranking, theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[0], theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[3], sortedListOfPureAdmissionsOfThePreviousThreeYears[0], volunteerItemsTotal, config),
        year2: calculateTheSingleYearAdmissionProbability(volunteerItem.ranking2, volunteerItem.num2, form.ranking, theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[1], theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[4], sortedListOfPureAdmissionsOfThePreviousThreeYears[1], volunteerItemsTotal, config),
        year3: calculateTheSingleYearAdmissionProbability(volunteerItem.ranking3, volunteerItem.num3, form.ranking, theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[2], theMaximumAndMinimumRankAndNumForEachOfThePreviousThreeYears[5], sortedListOfPureAdmissionsOfThePreviousThreeYears[2], volunteerItemsTotal, config),
    }
    let sum = 0
    if (volunteerItem['ranking1'] == 0) {
        volunteerItem['rate']['year1'] = 0
    } else {
        sum += 0.5
    }
    if (volunteerItem['ranking2'] == 0) {
        volunteerItem['rate']['year2'] = 0
    } else {
        sum += 0.3
    }
    if (volunteerItem['ranking3'] == 0) {
        volunteerItem['rate']['year3'] = 0
    } else {
        sum += 0.2
    }
    volunteerItem.rate['all'] = (volunteerItem['rate']['year1'] * allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears[0] + volunteerItem['rate']['year2'] * allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears[1] + volunteerItem['rate']['year3'] * allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears[2]) / sum
    return volunteerItem
}

function obtainASortedListOfTheNumberOfPureAdmissions(allVolunteerItems, yearSub) {
    let re = []
    for (let i = 0; i < allVolunteerItems.length; i++) {
        if (allVolunteerItems[i]['num' + yearSub.toString()] == 0) {
            break
        }
        if (re.length == 0 || re[re.length - 1][0] != allVolunteerItems[i]['num' + yearSub.toString()]) {
            re.push([allVolunteerItems[i]['num' + yearSub.toString()], 1])
        } else {
            re[re.length - 1][1] += 1
        }
    }
    return re
}

function threeTypesOfVolunteersAreGeneratedAccordingToTheDividingLineOfVolunteers(allVolunteerItems, config) {
    let re = [[], [], []]
    for (let i = 0; i < allVolunteerItems.length; i++) {
        if (allVolunteerItems[i].rate.all <= config.strikeProtectionTypeBoundaryProbabilityLine[1] && allVolunteerItems[i].rate.all >= config.strikeProtectionTypeBoundaryProbabilityLine[0]) {
            re[0].push(allVolunteerItems[i])
            continue
        }
        if (allVolunteerItems[i].rate.all <= config.strikeProtectionTypeBoundaryProbabilityLine[2] && allVolunteerItems[i].rate.all >= config.strikeProtectionTypeBoundaryProbabilityLine[0]) {
            re[1].push(allVolunteerItems[i])
            continue
        }
        if (allVolunteerItems[i].rate.all >= config.strikeProtectionTypeBoundaryProbabilityLine[0]) {
            re[2].push(allVolunteerItems[i])
        }
    }
    return {
        chong: re[0],
        chongLength: re[0].length,
        wen: re[1],
        wenLength: re[1].length,
        bao: re[2],
        baoLength: re[2].length,
    }
}

function waitForTheExecutionOfTheSqlStatementToComplete(sql) {
    return new Promise((resolve, reject) => {
        db.query(sql, (err, results) => {
            return resolve(results)
        })
    })
}

function random(n) {
    return parseInt(Math.random() * 100) % n + 1
}

function whetherTheCandidateHasChosenThisSubject(studentSubjectString, subjectName) {
    let subjectCode = 0
    switch (subjectName) {
        case '物理':
            subjectCode = '1'
            break;
        case '化学':
            subjectCode = '2'
            break;
        case '生物':
            subjectCode = '3'
            break;
        case '政治':
            subjectCode = '4'
            break;
        case '历史':
            subjectCode = '5'
            break;
        case '地理':
            subjectCode = '6'
            break;
    }
    return isSubstring(subjectCode, studentSubjectString.slice(1, 10))
}

let config = {
    fractionalIntervalSize: 1, //1最小区间 2最大区间
    theMinimumNumberOfYearsTheVolunteerHasBeenInTheScope: 3, //志愿选入的最少年数
    allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears: [0.5, 0.3, 0.2], //分配前三年录取概率的比例
    strikeProtectionTypeBoundaryProbabilityLine: [0.2, 0.5, 0.8],  //难冲稳保三种类型志愿的分界线
    theProportionOfTheNumberOfCandidatesAndTheNumberOfAdmissionsToTheProbability: [0.8, 0.2]  //志愿位次和录取人数在录取概率中的比例
}

app.post("/api/v1/fillApplication/autoFill", async (req, res, next) => {

    try {
        const form = JSON.parse(req.query.data)
        form.subjectScores = JSON.parse(form.subjectScores)
        let tables = await getAllOnePointOneSegmentTables()
        let scoreRanges = [getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year1), getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year2), getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year3)]
        let scoreRangesMin = [scoreRanges[0][0], scoreRanges[1][0], scoreRanges[2][0]].sort()
        let scoreRangesMax = [scoreRanges[0][1], scoreRanges[1][1], scoreRanges[2][1]].sort()
        let scoreRangeMaximum = [scoreRangesMin[0], scoreRangesMax[2]]
        let scoreRangeMinimum = [scoreRangesMin[2], scoreRangesMax[1]]
        let selectTheScoreRangeForTheVoluntaryItem = (config.fractionalIntervalSize == 1 ? scoreRangeMinimum : scoreRangeMaximum)
        let allVolunteers = removeVolunteersWhoseSubjectsDoNotMatchTheirPhysicalLimitations(await getAllTheVolunteersFromTheDatabase(), form)
        allVolunteers.sort(compareVolunteerItem(1, 'ranking'))
        let year1MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 1, 'ranking')
        allVolunteers.sort(compareVolunteerItem(2, 'ranking'))
        let year2MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 2, 'ranking')
        allVolunteers.sort(compareVolunteerItem(3, 'ranking'))
        let year3MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 3, 'ranking')
        allVolunteers.sort(compareVolunteerItem(1, 'num'))
        let year1MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 1, 'num')
        let year1SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 1)
        allVolunteers.sort(compareVolunteerItem(2, 'num'))
        let year2MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 2, 'num')
        let year2SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 2)
        allVolunteers.sort(compareVolunteerItem(3, 'num'))
        let year3MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 3, 'num')
        let year3SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 3)
        let theMaximumAndMinimumRankForEachOfThePreviousThreeYears = [year1MaximumAndMinimumRanking, year2MaximumAndMinimumRanking, year3MaximumAndMinimumRanking, year1MaximumAndMinimumNum, year2MaximumAndMinimumNum, year3MaximumAndMinimumNum]
        let chosenInTheFirstStep = []
        for (let i = 0; i < allVolunteers.length; i++) {
            if (whetherTheVolunteerProjectIsSelected(allVolunteers[i], selectTheScoreRangeForTheVoluntaryItem, config.theMinimumNumberOfYearsTheVolunteerHasBeenInTheScope, form)) {
                chosenInTheFirstStep.push(gainAcceptanceRate(allVolunteers[i], form, theMaximumAndMinimumRankForEachOfThePreviousThreeYears, config.allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears, [year1SortedListOfPureAdmissions, year2SortedListOfPureAdmissions, year3SortedListOfPureAdmissions], allVolunteers.length, config))
            }
        }
        chosenInTheFirstStep.sort(compareVolunteerItemByAllRate())


        let studentScores = [form.subjectScores.s1, form.subjectScores.s2, form.subjectScores.s3, 0, 0, 0, 0, 0, 0]
        for (let i = 0; i < 3; i++) {
            studentScores[i] = parseInt(studentScores[i] / 1.5)
            studentScores[parseInt(form.subjects.slice(i + 1, i + 2)) + 2] = form.subjectScores['s' + (i + 4).toString()]
        }
        console.log(studentScores)
        let max = -1
        let min = 101
        for (let i = 0; i < 9; i++) {
            if (studentScores[i] == 0) {
                continue
            }
            if (studentScores[i] > max) {
                max = studentScores[i]
            }
            if (studentScores[i] < min) {
                min = studentScores[i]
            }
        }
        let studentScoresCountSum = 0
        for (let i = 0; i < 9; i++) {
            studentScores[i] -= (min - 2)
            if (studentScores[i] < 0) {
                studentScores[i] = 0
            }
            studentScoresCountSum += studentScores[i]
        }
        let maxSubjectName = ''
        let maxSubjectRate = -1
        let subjectIndexs = {
            '语文': 0,
            '数学': 1,
            '外语': 2,
            '物理': 3,
            '化学': 4,
            '生物': 5,
            '政治': 6,
            '历史': 7,
            '地理': 8,
        }
        let subjectNames = {
            0: '语文',
            1: '数学',
            2: '外语',
            3: '物理',
            4: '化学',
            5: '生物',
            6: '政治',
            7: '历史',
            8: '地理',
        }
        for (let i = 0; i < 9; i++) {
            studentScores[i] = (studentScores[i] / studentScoresCountSum)
            if (studentScores[i] > maxSubjectRate) {
                maxSubjectRate = studentScores[i]
                maxSubjectName = subjectNames[i]
            }
        }
        let chosenInTheSecondStep = []
        let notChosenInTheSecondStep = []
        for (let i = 0; i < chosenInTheFirstStep.length; i++) {
            if (isInclude(chosenInTheFirstStep[i].tags.split(','), maxSubjectName) == true) {
                chosenInTheSecondStep.push(chosenInTheFirstStep[i])
            } else {
                notChosenInTheSecondStep.push(chosenInTheFirstStep[i])
            }
        }
        let subjectsMaxNums = []
        for (let i = 0; i < 9; i++) {
            if (subjectNames[i] == maxSubjectName) {
                subjectsMaxNums[i] = 0
                continue
            }
            subjectsMaxNums[i] = studentScores[i] / maxSubjectRate * chosenInTheSecondStep.length
        }
        let chosenInTheThirdStep = []
        for (let i = 0; i < notChosenInTheSecondStep.length; i++) {
            let flag = 0
            let cTags = notChosenInTheSecondStep[i].tags.split(',')
            let amountOfGrowth = 1 / cTags.length
            for (let i1 = 0; i1 < cTags.length; i1++) {
                if ((subjectsMaxNums[subjectIndexs[cTags[i1]]] - amountOfGrowth) >= 0) {
                    subjectsMaxNums[subjectIndexs[cTags[i1]]] -= amountOfGrowth
                    flag += 1
                }
            }
            if (flag > 0) {
                chosenInTheThirdStep.push(notChosenInTheSecondStep[i])
            }
        }
        let chongWenBao = threeTypesOfVolunteersAreGeneratedAccordingToTheDividingLineOfVolunteers(chosenInTheFirstStep, config)
        //拉进表
        let formName = '智能填报' + generateTimeString()
        let sqlString = ''
        let num = 1
        let groupSize = 0
        if (chongWenBao.chongLength <= 16) {
            groupSize = 1
        } else {
            groupSize = parseInt(chongWenBao.chongLength / 16)
        }
        for (let i = 0; i < chongWenBao.chongLength; i += groupSize) {
            if (num == 17) {
                break
            }
            if (i != 0) {
                sqlString += ','
            }
            rdm = random(groupSize - 1)
            if (isNaN(rdm) == true) {
                rdm = 0
            }
            sqlString += "(" + num.toString() + ",'" + chongWenBao.chong[i + rdm].majorName + "','" + chongWenBao.chong[i + rdm].universityName + "','" + form.account + "','" + formName + "')"
            num += 1
        }
        if (chongWenBao.wenLength <= 48) {
            groupSize = 1
        } else {
            groupSize = parseInt(chongWenBao.wenLength / 48)
        }
        console.log(groupSize, chongWenBao.wenLength)
        for (let i = 0; i < chongWenBao.wenLength; i += groupSize) {
            if (num == 65) {
                break
            }
            rdm = random(groupSize - 1)
            if (isNaN(rdm) == true) {
                rdm = 0
            }
            sqlString += ','
            sqlString += "(" + num.toString() + ",'" + chongWenBao.wen[i + rdm].majorName + "','" + chongWenBao.wen[i + rdm].universityName + "','" + form.account + "','" + formName + "')"
            num += 1
        }
        if (chongWenBao.baoLength <= 32) {
            groupSize = 1
        } else {
            groupSize = parseInt(chongWenBao.baoLength / 32)
        }
        for (let i = 0; i < chongWenBao.baoLength; i += groupSize) {
            if (num == 97) {
                break
            }
            rdm = random(groupSize - 1)
            if (isNaN(rdm) == true) {
                rdm = 0
            }
            sqlString += ','
            sqlString += "(" + num.toString() + ",'" + chongWenBao.bao[i + rdm].majorName + "','" + chongWenBao.bao[i + rdm].universityName + "','" + form.account + "','" + formName + "')"
            num += 1
        }
        await waitForTheExecutionOfTheSqlStatementToComplete("insert into applicationform(index0,majorName,universityName,userAccount,formName) values" + sqlString + ";")
        console.log(chosenInTheFirstStep.length)
        setTimeout(() => {
            res.send({
                status: 1,
                content: '填报成功'
            })
        }, 1000);

    } catch (err) {
        next(err)
    }
})

app.get("/api/v1/intelligentSelection/get", async (req, res) => {
    try {
        const data = JSON.parse(req.query.data)
        const form = data.form
        form.subjectScores = JSON.parse(form.subjectScores)
        let tables = await getAllOnePointOneSegmentTables()
        let scoreRanges = [getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year1), getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year2), getScoreRange(form.ranking, form.scoreUp, form.scoreDown, tables.year3)]
        let scoreRangesMin = [scoreRanges[0][0], scoreRanges[1][0], scoreRanges[2][0]].sort()
        let scoreRangesMax = [scoreRanges[0][1], scoreRanges[1][1], scoreRanges[2][1]].sort()
        let scoreRangeMaximum = [scoreRangesMin[0], scoreRangesMax[2]]
        let scoreRangeMinimum = [scoreRangesMin[2], scoreRangesMax[1]]
        let selectTheScoreRangeForTheVoluntaryItem = (config.fractionalIntervalSize == 1 ? scoreRangeMinimum : scoreRangeMaximum)
        let allVolunteers = removeVolunteersWhoseSubjectsDoNotMatchTheirPhysicalLimitations(await getAllTheVolunteersFromTheDatabase(), form)
        allVolunteers.sort(compareVolunteerItem(1, 'ranking'))
        let year1MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 1, 'ranking')
        allVolunteers.sort(compareVolunteerItem(2, 'ranking'))
        let year2MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 2, 'ranking')
        allVolunteers.sort(compareVolunteerItem(3, 'ranking'))
        let year3MaximumAndMinimumRanking = getTheMaximumAndMinimumForAYear(allVolunteers, 3, 'ranking')
        allVolunteers.sort(compareVolunteerItem(1, 'num'))
        let year1MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 1, 'num')
        let year1SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 1)
        allVolunteers.sort(compareVolunteerItem(2, 'num'))
        let year2MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 2, 'num')
        let year2SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 2)
        allVolunteers.sort(compareVolunteerItem(3, 'num'))
        let year3MaximumAndMinimumNum = getTheMaximumAndMinimumForAYear(allVolunteers, 3, 'num')
        let year3SortedListOfPureAdmissions = obtainASortedListOfTheNumberOfPureAdmissions(allVolunteers, 3)
        let theMaximumAndMinimumRankForEachOfThePreviousThreeYears = [year1MaximumAndMinimumRanking, year2MaximumAndMinimumRanking, year3MaximumAndMinimumRanking, year1MaximumAndMinimumNum, year2MaximumAndMinimumNum, year3MaximumAndMinimumNum]
        let chosenInTheFirstStep = []
        for (let i = 0; i < allVolunteers.length; i++) {
            allVolunteers[i] = gainAcceptanceRate(allVolunteers[i], form, theMaximumAndMinimumRankForEachOfThePreviousThreeYears, config.allocationOfProportionOfAdmissionProbabilityInTheFirstThreeYears, [year1SortedListOfPureAdmissions, year2SortedListOfPureAdmissions, year3SortedListOfPureAdmissions], allVolunteers.length, config)
            if (whetherTheVolunteerProjectIsSelected(allVolunteers[i], selectTheScoreRangeForTheVoluntaryItem, config.theMinimumNumberOfYearsTheVolunteerHasBeenInTheScope, form)) {
                chosenInTheFirstStep.push(allVolunteers[i])
            }
        }
        allVolunteers.sort(compareVolunteerItemByAllRate())
        chosenInTheFirstStep.sort(compareVolunteerItemByAllRate())
        let chongWenBao = threeTypesOfVolunteersAreGeneratedAccordingToTheDividingLineOfVolunteers(chosenInTheFirstStep, config)
        chongWenBao['all'] = chosenInTheFirstStep
        chongWenBao['allLength'] = chosenInTheFirstStep.length
        let re = []
        for (let i = (data.page - 1) * data.size; i < (data.page) * data.size; i++) {
            if (i > chongWenBao[data.type].length - 1) {
                break
            }
            re.push(chongWenBao[data.type][i])
        }
        res.send({
            chongLength: chongWenBao.chongLength,
            wenLength: chongWenBao.wenLength,
            baoLength: chongWenBao.baoLength,
            allLength: chosenInTheFirstStep.length,
            results: re
        })
        return
    } catch (error) {

    }
})

app.post("/api/v1/applicationForm/deleteSingleForm", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from applicationform where userAccount = '" + data.account + "' and formName = '" + data.formName + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: "删除成功"
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/moveTo", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        data.moveTo = parseInt(data.moveTo);
        data.current = parseInt(data.current);
        if (data.moveTo == data.current) {
            res.send({
                status: 1,
                content: '移动成功'
            })
            return;
        }
        let applicationformData = undefined;
        db.query("select * from applicationform where userAccount = '" + data.account + "'" + " and formName = '" + data.formName + "'" + " order by index0 ASC", (err, results0) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '移动失败'
                })
                return
            }
            applicationformData = results0;
            if (data.moveTo < data.current) {
                const total = data.current - data.moveTo;
                let count = 0;
                for (let i = data.moveTo; i < data.current; i++) {
                    db.query("update applicationform set index0 = " + (i + 1) + " where majorName = '" + results0[i - 1].majorName + "' and universityName = '" + results0[i - 1].universityName + "' and userAccount = '" + data.account + "'" + " and formName = '" + data.formName + "'", (err, results) => {
                        count += 1;
                        if (count == total) {
                            db.query("update applicationform set index0 = " + data.moveTo + " where majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "' and userAccount = '" + data.account + "'" + " and formName = '" + data.formName + "'", (err, results1) => {
                                res.send({
                                    status: 1,
                                    content: '移动成功'
                                })
                            })
                        }
                    })
                }
            } else {
                const total = data.moveTo - data.current;
                let count = 0;
                for (let i = data.moveTo; i > data.current; i--) {
                    db.query("update applicationform set index0 = " + (i - 1) + " where majorName = '" + results0[i - 1].majorName + "' and universityName = '" + results0[i - 1].universityName + "' and userAccount = '" + data.account + "'" + " and formName = '" + data.formName + "'", (err, results) => {
                        count += 1;
                        if (count == total) {
                            db.query("update applicationform set index0 = " + data.moveTo + " where majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "' and userAccount = '" + data.account + "'" + " and formName = '" + data.formName + "'", (err, results1) => {
                                res.send({
                                    status: 1,
                                    content: '移动成功'
                                })
                            })
                        }
                    })
                }
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/bigdata/scoreranking", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from scoreranking where year = " + subtractYear(1) + " order by ranking ASC", (err, re1) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                let score1 = undefined;
                if (re1.length != 0 && re1[0].ranking < parseInt(data.ranking)) {
                    for (let i = 0; i < re1.length - 1; i++) {
                        if (re1[i].ranking <= parseInt(data.ranking) && re1[i + 1].ranking >= parseInt(data.ranking)) {
                            score1 = [re1[i].score, re1[i + 1].score];
                            break;
                        }
                    }
                }
                let data1 = [];
                let data11 = [];
                for (let i = 0; i < re1.length; i++) {
                    data1.push(re1[i].score);
                    data11.push(re1[i].ranking - (i == 0 ? 0 : re1[i - 1].ranking));
                }
                db.query("select * from scoreranking where year = " + subtractYear(2) + " order by ranking ASC", (err, re2) => {
                    if (err) {
                        res.send({
                            status: 0,
                            content: '获取失败'
                        })
                    } else {
                        let score2 = undefined;
                        if (re2.length != 0 && re2[0].ranking < parseInt(data.ranking)) {
                            for (let i = 0; i < re2.length - 1; i++) {
                                if (re2[i].ranking <= parseInt(data.ranking) && re2[i + 1].ranking >= parseInt(data.ranking)) {
                                    score2 = [re2[i].score, re2[i + 1].score];
                                    break;
                                }
                            }
                        }
                        let data2 = [];
                        let data21 = [];
                        for (let i = 0; i < re2.length; i++) {
                            data2.push(re2[i].score);
                            data21.push(re2[i].ranking - (i == 0 ? 0 : re2[i - 1].ranking));
                        }
                        db.query("select * from scoreranking where year = " + subtractYear(3) + " order by ranking ASC", (err, re3) => {
                            if (err) {
                                res.send({
                                    status: 0,
                                    content: '获取失败'
                                })
                            } else {
                                let score3 = undefined;
                                if (re3.length != 0 && re3[0].ranking < parseInt(data.ranking)) {
                                    for (let i = 0; i < re3.length - 1; i++) {
                                        if (re3[i].ranking <= parseInt(data.ranking) && re3[i + 1].ranking >= parseInt(data.ranking)) {
                                            score3 = [re3[i].score, re3[i + 1].score];
                                            break;
                                        }
                                    }
                                }
                                let data3 = [];
                                let data31 = [];
                                for (let i = 0; i < re3.length; i++) {
                                    data3.push(re3[i].score);
                                    data31.push(re3[i].ranking - (i == 0 ? 0 : re3[i - 1].ranking));
                                }
                                res.send({
                                    status: 1,
                                    content: '获取成功',
                                    results: {
                                        data1: data1,
                                        data11: data11,
                                        score1: score1,
                                        data2: data2,
                                        data21: data21,
                                        score2: score2,
                                        data3: data3,
                                        data31: data31,
                                        score3: score3
                                    }
                                })
                            }
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/vip/positive", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from vips where keyString = '" + data.keyString + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '激活失败，原因：系统错误'
                })
            } else {
                if (results.length == 0) {
                    res.send({
                        status: 0,
                        content: '激活失败，原因：此序列号不存在'
                    })
                } else {
                    const currentYear = new Date().getFullYear();
                    if (results[0].year == currentYear.toString()) {
                        db.query("update vips set account = '" + data.account + "' where keyString = '" + data.keyString + "'", (err, results1) => {
                            if (err) {
                                res.send({
                                    status: 0,
                                    content: '激活失败，原因：系统错误'
                                })
                            } else {
                                res.send({
                                    status: 1,
                                    content: '激活成功'
                                })
                            }
                        })
                    } else {
                        res.send({
                            status: 0,
                            content: '激活失败，原因：此序列号未到使用时间或已过使用时间'
                        })
                    }
                }
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/vip/search", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from vips where keyString like '%" + data.keyString + "%' and account like '%" + data.account + "%' and year like '%" + data.year + "%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/vip/import", (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            if (isJSONString(formData)) {
                const predata = convertStringToArray(JSON.parse(formData).data)
                const total = predata.length;
                let count = 0;
                for (let i = 0; i < total; i++) {
                    db.query("insert into vips values('" + predata[i] + "','-','" + JSON.parse(formData).year + "')", (err, results) => {
                        count += 1;
                        if (count == total) {
                            res.send({
                                status: 1,
                                content: '导入成功'
                            })
                            return;
                        }
                    })
                }
            } else {
                res.send({
                    status: 2,
                    content: '重新发送'
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/system/getAll", (req, res, next) => {
    try {
        db.query("select * from systemsettings", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                res.send({
                    status: 1,
                    contnet: '获取成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/system/get", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select value from systemsettings where keyName = '" + data.keyName + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '获取成功',
                    results: results[0]
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/system/update", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("update systemsettings set value = '" + data.value + "' where keyName = '" + data.key + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/users/teacherLogin", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users where userType = 2 and account = '" + data.account + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '登录失败'
                })
            } else {
                if (results.length == 0) {
                    res.send({
                        status: 0,
                        content: '用户不存在'
                    })
                } else {
                    if (results[0].password == data.password) {
                        res.send({
                            status: 1,
                            content: '登录成功',
                            results: results[0]
                        })
                    } else {
                        res.send({
                            status: 0,
                            content: '密码错误'
                        })
                    }
                }
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/teacher/getList", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from chat order by time ASC", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                let pre1 = [];
                for (let i = 0; i < results.length; i++) {
                    if ((results[i].fromAccount == data.account1 && results[i].toAccount == data.account2) || (results[i].fromAccount == data.account2 && results[i].toAccount == data.account1)) {
                        pre1.push(results[i]);
                    }
                }
                results = pre1;;
                let re = [];
                for (let i = 0; i < results.length; i++) {
                    let flag = true;
                    for (let i1 = 0; i1 < re.length; i1++) {
                        if (re[i1].time == results[i].time) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        re.push({
                            time: results[i].time,
                            items: []
                        })
                    }
                }
                for (let i = 0; i < re.length; i++) {
                    for (let i1 = 0; i1 < results.length; i1++) {
                        if (results[i1].time == re[i].time) {
                            re[i].items.push(results[i1]);
                        }
                    }
                }
                for (let i = 0; i < unreadNums.length; i++) {
                    if (unreadNums[i].fromAccount == data.account1 && unreadNums[i].toAccount == data.account2) {
                        let pre = [];
                        for (let i1 = 0; i1 < unreadNums.length; i1++) {
                            if (unreadNums[i1].fromAccount == data.account1 && unreadNums[i1].toAccount == data.account2) {
                                continue;
                            }
                            pre.push(results[i1]);
                        }
                        unreadNums = pre;
                        break;
                    }
                }
                let loginStatus = false;
                for (let i = 0; i < userStatus.length; i++) {
                    if (userStatus[i].account == data.account2) {
                        if (userStatus[i].status == 1) {
                            loginStatus = true;
                            break;
                        }
                    }
                }
                res.send({
                    status: 1,
                    content: '获取成功',
                    results: re,
                    loginStatus: loginStatus
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/teacher/getChatList", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users where teacherAccount = '" + data.account + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                for (let i = 0; i < results.length; i++) {
                    results[i]['unreadNum'] = 0;
                }
                for (let i = 0; i < results.length; i++) {
                    for (let i1 = 0; i1 < unreadNums.length; i1++) {
                        if (unreadNums[i1].fromAccount == results[i].account && unreadNums[i1].toAccount == data.account) {
                            results[i].unreadNum = unreadNums[i1].count;
                            break;
                        }
                    }
                }
                res.send({
                    status: 1,
                    content: "获取成功",
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/teacher/send", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into chat values('" + data.fromAccount + "','" + data.toAccount + "'," + data.type + ",'" + data.content + "','" + data.time + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '发送失败'
                })
            } else {
                for (let i = 0; i < userStatus.length; i++) {
                    if (userStatus[i].account == data.fromAccount) {
                        userStatus[i].status = 1;
                        break;
                    }
                }
                let flag = true;
                for (let i = 0; i < unreadNums.length; i++) {
                    if (unreadNums[i].fromAccount == data.fromAccount && unreadNums[i].toAccount == data.toAccount) {
                        unreadNums[i].count += 1;
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    unreadNums.push({
                        fromAccount: data.fromAccount,
                        toAccount: data.toAccount,
                        count: 1,
                    })
                }
                res.send({
                    status: 1,
                    content: '发送成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/users/updateStatus", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        for (let i = 0; i < userStatus.length; i++) {
            if (userStatus[i].account == data.account) {
                userStatus[i].status = 1;
                res.send({
                    status: 1,
                    content: '更新成功'
                })
                return;
            }
        }
        userStatus.push({
            account: data.account,
            status: 1,
        })
        res.send({
            status: 1,
            content: '更新成功'
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/teacher/get", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users where account = '" + data.account + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '获取成功',
                    results: results[0]
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/teacher/start", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users where userType = 2", (err, results) => {
            if (results.length == 0) {
                res.send({
                    content: '暂无咨询师',
                    status: 0,
                })
                return;
            }
            if (results.length == 0) {
                db.query("insert into users values('" + account + "','" + data.password + "','" + data.name + "','" + data.home + "','" + data.subjects + "'," + data.score + ",'" + data.ranking + "','" + data.idNumber + "',1,'',0,0)", (err, results) => {
                    if (err) {
                        res1 = {
                            status: 0,
                            content: '请求失败',
                        }
                        res.send(JSON.stringify(res1))
                    } else {
                        res.send({
                            status: 1,
                            content: '添加成功'
                        })
                    }
                })
                return;
            }
            let total = results.length;
            let count = 0;
            let min = {
                account: undefined,
                num: 99999999,
            }
            for (let i = 0; i < results.length; i++) {
                db.query("select * from users where account = '" + results[i].teacherAccount + "'", (err, results1) => {
                    if (results1.length < min.num) {
                        min.num = results1.length;
                        min.account = results[i].account;
                        count += 1;
                        if (count == total) {
                            db.query("update users set teacherAccount = '" + min.account + "' where account = '" + data.account + "'", (err, results2) => {
                                if (err) {
                                    res1 = {
                                        status: 0,
                                        content: '请求失败',
                                    }
                                    res.send(JSON.stringify(res1))
                                } else {
                                    res.send({
                                        status: 1,
                                        content: '添加成功1'
                                    })
                                    db.query("delete from chat where fromAccount = '" + data.account + "' and toAccount = '" + min.account + "'", (err, results3) => {
                                    });
                                    db.query("delete from chat where toAccount = '" + data.account + "' and fromAccount = '" + min.account + "'", (err, results3) => {
                                    });
                                }
                            })
                            return;
                        }
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/universities/list", (req, res, next) => {
    try {
        axios.get('http://tools.fuwuce.com/top/school.html')
            .then(response => {
                const $ = cheerio.load(response.data);
                const tables = $('.p5 table');
                const result = [];

                tables.each(function () {
                    const table = $(this);
                    const rows = table.find('tbody tr');

                    rows.each(function () {
                        const row = $(this);
                        const columns = row.find('td');
                        const rowData = [];

                        columns.each(function () {
                            const column = $(this);
                            rowData.push(column.text().trim());
                        });

                        result.push(rowData);
                    });
                });

                res.send({
                    status: 1,
                    content: '获取成功',
                    results: result
                })

                return result;
            })
            .catch(error => {
                throw new Error('Failed to fetch table data');
            });
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/up", (req, res, next) => {
    try {


        const data = JSON.parse(req.query.data);
        db.query("select * from applicationform where userAccount = '" + data.userAccount + "'" + " and formName = '" + data.formName + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '上移失败'
                })
            } else {
                const total = results.length;
                let lastIndex = data.index0;
                db.query("update applicationform set index0 = " + data.index0 + " where userAccount = '" + data.userAccount + "' and index0 = " + (data.index0 - 1) + " and formName = '" + data.formName + "'", (err, results1) => {
                    if (err) {
                        res.send({
                            status: 0,
                            content: '上移失败'
                        })
                    } else {
                        db.query("update applicationform set index0 = " + (data.index0 - 1) + " where userAccount = '" + data.userAccount + "' and majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "'" + " and formName = '" + data.formName + "'", (err, results2) => {
                            if (err) {
                                res.send({
                                    status: 0,
                                    content: '上移失败'
                                })
                            } else {
                                res.send({
                                    status: 1,
                                    content: '上移成功'
                                })
                            }
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/down", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from applicationform where userAccount = '" + data.userAccount + "'" + " and formName = '" + data.formName + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '下移失败'
                })
            } else {
                const total = results.length;
                let lastIndex = data.index0;
                db.query("update applicationform set index0 = " + data.index0 + " where userAccount = '" + data.userAccount + "' and index0 = " + (data.index0 + 1) + " and formName = '" + data.formName + "'", (err, results1) => {
                    if (err) {
                        res.send({
                            status: 0,
                            content: '下移失败'
                        })
                    } else {
                        db.query("update applicationform set index0 = " + (data.index0 + 1) + " where userAccount = '" + data.userAccount + "' and majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "'" + " and formName = '" + data.formName + "'", (err, results2) => {
                            if (err) {
                                res.send({
                                    status: 0,
                                    content: '下移失败'
                                })
                            } else {
                                res.send({
                                    status: 1,
                                    content: '下移成功'
                                })
                            }
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/deleteSingle", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from applicationform where userAccount = '" + data.userAccount + "' and majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "'" + " and formName = '" + data.formName + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                db.query("select * from applicationform where userAccount = '" + data.userAccount + "'" + " and formName = '" + data.formName + "'", (err, results1) => {
                    if (err) {
                        res.send({
                            status: 0,
                            content: '删除失败'
                        })
                    } else {
                        const total = results1.length;
                        let count = 0;
                        if (total == 0) {
                            res.send({
                                status: 1,
                                content: '删除成功',
                            })
                            return;
                        }
                        for (let i = 0; i < results1.length; i++) {
                            if (results1[i].index0 <= data.index0) {
                                count += 1;
                                if (count == total) {
                                    res.send({
                                        status: 1,
                                        content: '删除成功',
                                    })
                                }
                                continue;
                            }
                            db.query("update applicationform set index0 = " + (results1[i].index0 - 1) + " where userAccount = '" + results1[i].userAccount + "' and majorName = '" + results1[i].majorName + "' and universityName = '" + results1[i].universityName + "'" + " and formName = '" + data.formName + "'", (err, results2) => {
                                if (err) {
                                }
                                count += 1;
                                if (count == total) {
                                    res.send({
                                        status: 1,
                                        content: '删除成功',
                                    })
                                }
                            })
                        }
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/applicationForm/getFormList", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select distinct formName from applicationform where userAccount = '" + data.account + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            } else {
                let pre = [];
                for (let i = 0; i < results.length; i++) {
                    pre.push(results[i].formName);
                }
                res.send({
                    status: 1,
                    content: '获取成功',
                    results: pre
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/deleteAll", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from applicationform where userAccount = '" + data.userAccount + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '删除成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/applicationForm/add", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from applicationform where userAccount = '" + data.userAccount + "' and formName = '" + data.formName + "'", (err, result0) => {
            const total = result0.length;
            db.query("select * from applicationform where userAccount = '" + data.userAccount + "' and majorName = '" + data.majorName + "' and universityName = '" + data.universityName + "' and formName = '" + data.formName + "'", (err, results) => {
                if (err) {
                    res.send({
                        status: 0,
                        content: '添加失败'
                    })
                } else {
                    if (results.length == 1) {
                        res.send({
                            status: 0,
                            content: '该志愿已在志愿表中'
                        })
                        return;
                    }
                    let index = total + 1;
                    db.query("insert into applicationform values('" + data.userAccount + "','" + data.majorName + "','" + data.universityName + "'," + index + ",'" + data.formName + "')", (err, results1) => {
                        if (err) {
                            res.send({
                                status: 0,
                                content: '添加失败'
                            })
                        } else {
                            res.send({
                                status: 1,
                                content: '添加成功'
                            })
                        }
                    })
                }
            })
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }

})

app.get("/api/v1/applicationForm/get", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        // select * from applicationform t1,majors t2 where userAccount=? and formName=? and majorName=? and t1.universityName=t2.universityName and t1.majorName=t2.majorName
        // 
        db.query("select * from applicationform t1,majors t2 where userAccount=? and formName=? and t1.universityName=t2.universityName and t1.majorName=t2.majorName", [data.userAccount, data.formName,], (err, results) => {

            results.sort((a, b) => {
                return a.index0 - b.index0
            })

            res.send({
                status: 1,
                content: '获取成功',
                results: results
            })
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }


})

app.get("/api/v1/applicationForm/get2", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from applicationform where userAccount = '" + data.userAccount + "' and formName = '" + data.formName + "'", (err, results) => {
            const total = results.length;
            if (total == 0) {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: [],
                })
                return;
            }
            let count = 0;
            let re = [];
            for (let i = 0; i < total; i++) {
                db.query("select * from majors where majorName = '" + results[i].majorName + "' and universityName = '" + results[i].universityName + "'", (err, results1) => {
                    re.push(results1[0]);
                    re[re.length - 1]['index0'] = results[i].index0;
                    count += 1;
                    if (count == total) {
                        if (err) {
                            res.send({
                                status: 0,
                                contnet: '获取失败'
                            })
                        } else {
                            for (let i1 = 0; i1 < re.length; i1++) {
                                let flag = true;
                                for (let i2 = 1; i2 < re.length - i1; i2++) {
                                    if (re[i2].index0 < re[i2 - 1].index0) {
                                        let temp = re[i2];
                                        re[i2] = re[i2 - 1];
                                        re[i2 - 1] = temp;
                                        flag = false;
                                    }
                                }
                                if (flag) {
                                    break;
                                }
                            }
                            res.send({
                                status: 1,
                                content: '获取成功',
                                results: re
                            })
                        }
                    }
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }

})

app.get("/api/v1/fillApplication/search", (req, res, next) => {
    try {

        const searchForm = JSON.parse(req.query.data)
        let addSql = conditionSql(searchForm)


        const sql =
            `select * from majors where ${addSql} limit 10 offset ${(searchForm.current - 1) * 10}`


        db.query(sql, (err, result) => {
            if (err) {
                res.send({})
            }
            addDisabled(result, searchForm)




            db.query(`select count(*) count from majors where ${addSql}`, (err, res2) => {
                res.send({
                    results: result,
                    count: Math.ceil(res2[0].count / 10)
                })
            })

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }

})

app.get("/api/v1/favoritemajorcontents/get", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from favoritemajorcontents where userAccount = '" + data.userAccount + "'", (err, results) => {
            const total = results.length;
            let count = 0;
            if (total == 0) {
                res.send({
                    status: 0,
                    content: '获取成功',
                    results: []
                })
                return;
            }
            for (let i = 0; i < results.length; i++) {
                db.query("select * from majorcontents where majorName = '" + results[i].name + "'", (err, results1) => {

                    count += 1;
                    results[i]['info'] = results1;
                    if (count == total) {
                        res.send({
                            status: 1,
                            content: '获取成功',
                            results: results
                        })
                    }
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/favoriteuniversities/get", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from favoriteuniversities where userAccount = '" + data.userAccount + "'", (err, results) => {
            const total1 = results.length;
            let count1 = 0;
            if (total1 == 0) {
                res.send({
                    status: 0,
                    content: '获取成功',
                    results: []
                })
                return;
            }
            for (let i = 0; i < results.length; i++) {
                db.query("select * from universities where name = '" + results[i].name + "'", (err, results1) => {
                    count1 += 1;
                    results[i]['info'] = results1;
                    if (count1 == total1) {
                        const total = results.length;
                        if (total == 0) {
                            res.send({
                                status: 1,
                                content: '查询成功',
                                results: []
                            })
                            return;
                        }
                        let count = 0;
                        for (let i = 0; i < results.length; i++) {
                            db.query("select * from cities where name like '%" + results[i].info[0].city.slice(0, 2) + "%'", (err, results2) => {
                                count += 1;
                                results[i]['cityLevel'] = results2[0].level;
                                if (count == total) {
                                    res.send({
                                        status: 1,
                                        content: '查询成功',
                                        results: results
                                    })
                                }
                            })
                        }
                    }
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/favoriteMajorContents/delete", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from favoritemajorcontents where name = '" + data.name + "' and userAccount = '" + data.userAccount + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '取消收藏失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '取消收藏成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/favoriteMajorContents/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into favoritemajorcontents values('" + data.name + "','" + data.userAccount + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '收藏失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '收藏成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/majorcontents/introduction", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        const axios = require('axios');


        db.query("select * from majorcontents where majorName = '" + data.name + "'", (err, results) => {
            db.query("select * from favoritemajorcontents where name = '" + data.name + "' and userAccount = '" + data.userAccount + "'", (err, results1) => {
                axios.get("https://static-data.gaokao.cn/www/2.0/info/linkage.json").then((reszs1) => {
                    const majorcontentsfromzs = reszs1.data.data.special;
                    console.log(majorcontentsfromzs)
                    let majorzsid = '';
                    for (let i = 0; i < majorcontentsfromzs.length; i++) {
                        if (majorcontentsfromzs[i].name == data.name) {
                            majorzsid = majorcontentsfromzs[i].id;
                            break;
                        }
                    }
                    axios.get("https://static-data.gaokao.cn/www/2.0/special/" + majorzsid + "/pc_special_detail.json").then((reszs2) => {
                        console.log(reszs2.data.data)
                        res.send({
                            status: 1,
                            summary: '1',
                            logoPics: [],
                            homePage: '1',
                            results: results,
                            isFavorited: (results1.length == 0 ? false : true),
                            res1: reszs2.data.data
                        })
                    })

                })
            })

        })

    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get("/api/v1/majorcontents/userSearch", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select distinct class,remark from majorcontents where remark = '" + data.remark + "' and majorName like '%" + data.majorName + "%'", (err, results) => {
            const total = results.length;
            let count = 0;
            let total2 = 0;
            let count2 = 0;
            if (results.length == 0) {
                res.send({
                    status: 1,
                    content: '搜索成功',
                    results: []
                })
                return;
            }
            for (let i = 0; i < total; i++) {
                db.query("select distinct majorClass from majorcontents where class = '" + results[i].class + "' and remark = '" + data.remark + "' and majorName like '%" + data.majorName + "%'", (err, results1) => {
                    results[i]['majorClass'] = results1;
                    count += 1;
                    total2 += results1.length;
                    if (count == total) {
                        for (let i1 = 0; i1 < results.length; i1++) {
                            for (let i2 = 0; i2 < results[i1].majorClass.length; i2++) {

                                db.query("select majorName,majorId,degree,year,addYear from majorcontents where class = '" + results[i1].class + "' and majorClass = '" + results[i1].majorClass[i2].majorClass + "' and remark = '" + data.remark + "' and majorName like '%" + data.majorName + "%'", (err, results2) => {
                                    results[i1].majorClass[i2]['majors'] = results2;
                                    count2 += 1;
                                    if (count2 == total2) {
                                        res.send({
                                            status: 1,
                                            content: '搜索成功',
                                            results: results
                                        })
                                    }
                                })
                            }
                        }
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/favoriteUniversities/delete", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from favoriteuniversities where name = '" + data.name + "' and userAccount = '" + data.userAccount + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '取消收藏失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '取消收藏成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/favoriteUniversities/add", (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into favoriteuniversities values('" + data.name + "','" + data.userAccount + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '收藏失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '收藏成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/universities/userSearch', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        if (data.account == '' && data.current >= 2) {
            res.send({
                status: -7,
                content: '未登录'
            })
            return;
        }
        db.query("select * from universities where name like '%" + data.universityName + "%' and province like '%" + data.province + "%' and focus like '%" + (data.focus == "985,211" ? "985211" : data.focus) + "%' and level like '%" + data.level + "%'", (err, results1) => {
            const totalUniversities = results1.length;
            db.query("select * from universities where name like '%" + data.universityName + "%' and province like '%" + data.province + "%' and focus like '%" + (data.focus == "985,211" ? "211" : data.focus) + "%' and focus like '%" + (data.focus == "985,211" ? "985" : data.focus) + "%' and level like '%" + data.level + "%' order by minScore DESC limit " + data.start + "," + data.size, (err, results) => {
                if (err) {
                    res.send({
                        status: 0,
                        content: '搜索失败'
                    })
                } else {
                    const total = results.length;
                    if (total == 0) {
                        res.send({
                            status: 1,
                            content: '查询成功',
                            results: []
                        })
                        return;
                    }
                    let count = 0;
                    for (let i = 0; i < results.length; i++) {
                        db.query("select * from cities where name like '%" + results[i].city.slice(0, 2) + "%'", (err, results1) => {
                            count += 1;
                            if (results1.length != 0) {
                                results[i]['cityLevel'] = results1[0].level;
                            } else {
                                results[i]['cityLevel'] = '';
                            }
                            if (count == total) {
                                const currentYear = new Date().getFullYear();
                                db.query("select * from vips where account = '" + data.account + "' and year = '" + currentYear.toString() + "'", (err, result000) => {
                                    if (err) {
                                        res.send({
                                            status: 0,
                                            content: '查询失败'
                                        })
                                    } else {
                                        if (result000.length == 0 && data.current >= 2) {
                                            res.send({
                                                status: -7,
                                                content: '非VIP用户'
                                            })
                                        } else {
                                            res.send({
                                                status: 1,
                                                content: '查询成功',
                                                results: results,
                                                total: totalUniversities
                                            })
                                        }
                                    }
                                })

                            }
                        })
                    }
                }
            })
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }

})

app.post('/api/v1/universities/refresh', (req, res, next) => {
    try {
        db.query("select * from universities", (err, results) => {
            const total = results.length;
            let count = 0;
            for (let i = 0; i < results.length; i++) {
                db.query("select score1,ranking1 from majors where universityName = '" + results[i].name + "' and ranking1 not in (0) order by ranking1 DESC,score1", (err, results1) => {
                    let minScore = 0;
                    let minRanking = 0;
                    if (results1.length != 0) {
                        minScore = results1[0].score1,
                            minRanking = results1[0].ranking1
                    }
                    db.query("update universities set minScore = " + minScore + ",minRanking = " + minRanking + " where name = '" + results[i].name + "'", (err, results2) => {
                        count += 1;
                        if (err) {
                            res.send({
                                status: 0,
                                contnet: '更新失败'
                            })
                            return;
                        } else {
                            if (total == count) {
                                res.send({
                                    status: 1,
                                    content: '更新成功'
                                })
                            }
                        }

                    })
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/cities/search', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from cities where name like '%" + data.name + "%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/cities/deleteSelected', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            const predata = JSON.parse(formData)
            const total = predata.length;
            let count = 0;
            for (let i = 0; i < predata.length; i++) {
                db.query("delete from cities where name like '%" + predata[i] + "%'", (err, results) => {
                    count += 1;
                    if (count == total) {
                        res.send({
                            status: 1,
                            content: '删除成功',
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/cities/update', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("update cities set level = '" + data.level + "' where name = '" + data.name + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post("/api/v1/cities/deleteAll", (req, res, next) => {
    try {
        db.query("delete from cities where name like '%%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '删除成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/cities/import', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            if (isJSONString(formData)) {
                const predata = JSON.parse(formData)
                const total = predata.length;
                let count = 0;
                for (let i = 0; i < predata.length; i++) {
                    db.query("insert into cities values('" + (predata[i].name == undefined ? '' : predata[i].name) + "','" + (predata[i].level == undefined ? '' : predata[i].level) + "')", (err, results) => {
                        count += 1;
                        if (count == total) {
                            res.send({
                                status: 1,
                                content: '添加成功',
                            })
                        }
                    })
                }
            } else {
                res.send({
                    status: 2,
                    content: '重新发送'
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/cities/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into cities values('" + data.name + "','" + data.level + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '添加失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '添加成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/admin/login', (req, res, next) => {
    try {
        db.query("select * from admins where account = '" + req.query.account + "'", (err, results) => {
            if (results.length == 0) {
                res.send({
                    status: 2,
                    content: '用户不存在'
                })
            } else {
                if (results[0].password == req.query.password) {
                    res.send({
                        status: 1,
                        content: '登录成功'
                    })
                } else {
                    res.send({
                        status: 0,
                        content: '密码错误'
                    })
                }
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/majorcontents/search', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from majorcontents where class like '%" + data.class + "%' and majorClass like '%" + data.majorClass + "%' and majorName like '%" + data.majorName + "%' and majorId like '%" + data.majorId + "%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majorcontents/deleteAll', (req, res, next) => {
    try {
        db.query("delete from majorcontents where class like '%%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    contnet: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    contnet: '删除成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majorcontents/deleteSelected', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            const predata = JSON.parse(formData)
            const total = predata.length;
            let count = 0;
            for (let i = 0; i < predata.length; i++) {

                db.query("delete from majorcontents where majorId like '%" + predata[i] + "%'", (err, results) => {
                    count += 1;
                    if (count == total) {
                        res.send({
                            status: 1,
                            content: '删除成功',
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majorcontents/import', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            if (isJSONString(formData)) {
                const predata = JSON.parse(formData)
                const total = predata.length;
                let count = 0;
                for (let i = 0; i < predata.length; i++) {

                    db.query("insert into majorcontents values('" + (predata[i].class == undefined ? '' : predata[i].class) + "','" + (predata[i].majorClass == undefined ? '' : predata[i].majorClass) + "','" + (predata[i].majorName == undefined ? '' : predata[i].majorName) + "','" + (predata[i].majorId == undefined ? '' : predata[i].majorId) + "','" + (predata[i].degree == undefined ? '' : predata[i].degree) + "','" + (predata[i].year == undefined ? '0' : predata[i].year) + "','" + (predata[i].addYear == undefined ? '' : predata[i].addYear) + "','" + (predata[i].remark == undefined ? '' : predata[i].remark) + "')", async (err, results) => {
                        count += 1;
                        if (count == total) {
                            res.send({
                                status: 1,
                                content: '添加成功',
                            })
                            majorContents = await getTheMajorContentsTable()
                        }
                    })
                }
            } else {
                console.log("chongxi发送")
                res.send({
                    status: 2,
                    content: '重新发送'
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majorcontents/update', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);

        db.query("update majorcontents set class='" + data.class + "',majorClass='" + data.majorClass + "',majorName='" + data.majorName + "',degree='" + data.degree + "',year='" + data.year + "',addYear='" + data.addYear + "',remark='" + data.remark + "' where majorId = '" + data.majorId + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majorcontents/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);

        db.query("insert into majorcontents values('" + data.class + "','" + data.majorClass + "','" + data.majorName + "','" + data.majorId + "','" + data.degree + "','" + data.year + "','" + data.addYear + "','" + data.remark + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '添加失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '添加成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/users/getuserinfo', (req, res, next) => {
    try {
        db.query("select account, name, identity, home, school, grade, subjects, score, ranking, type from users where account = '" + req.query.account + "'", (err, results) => {
            if (err) {
                res1 = {
                    status: -1,
                    content: '请求失败',
                }
                res.send(JSON.stringify(res1))
            } else {
                results[0]['subjectScores'] = JSON.parse(results[0]['subjectScores'])
                res.send(JSON.stringify(results[0]))
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/users/login', (req, res, next) => {
    try {
        db.query("select password from users where account = '" + JSON.parse(req.query.data).account + "' and userType = 1", (err, results) => {
            if (err) {
                res1 = {
                    status: -1,
                    content: '请求失败',
                }
                res.send(JSON.stringify(res1))
            } else {

                if (results.length == 0) {
                    res.send({
                        status: 2,
                        content: '用户不存在',
                    })
                    return;
                }

                if (results[0].password == JSON.parse(req.query.data).password) {

                    db.query("select * from users where account = '" + JSON.parse(req.query.data).account + "'", (err1, results1) => {
                        if (err1) {
                            res1 = {
                                status: -2,
                                content: '请求失败',
                            }
                        } else {
                            db.query("select * from vips where account = '" + JSON.parse(req.query.data).account + "'", (err, results2) => {
                                if (err) {
                                    res.send({
                                        status: -3,
                                        content: '请求失败'
                                    })
                                } else {
                                    const currentYear = new Date().getFullYear();
                                    let isVip = 0;
                                    for (let i = 0; i < results2.length; i++) {
                                        if (results2[i].account == JSON.parse(req.query.data).account && results2[i].year == currentYear.toString()) {
                                            isVip = true;
                                            break;
                                        }
                                    }
                                    results1[0]['isVip'] = isVip;
                                    res.send(JSON.stringify({
                                        status: 1,
                                        content: '登录成功',
                                        data: results1[0],
                                    }))
                                }
                            })

                        }
                    })

                } else {
                    res.send({
                        status: 0,
                        content: '密码错误',
                    })
                }
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majors/deleteAll', (req, res, next) => {
    try {
        db.query("delete from majors where majorCode like '%%'", (err, results) => {
            res.send({
                status: 1,
                content: '删除成功'
            })
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/universities/introduction', (req, res, next) => {
    try {
        const axios = require('axios');
        const schoolName = req.query.name;
        let schoolId = undefined;
        axios.get('https://static-data.gaokao.cn/www/2.0/info/linkage.json')
            .then(res2 => {
                const gaokaoSchoolDatas = res2.data.data.school;
                for (let i = 0; i < gaokaoSchoolDatas.length; i++) {
                    if (gaokaoSchoolDatas[i].name == schoolName) {
                        schoolId = gaokaoSchoolDatas[i].school_id;
                        break;
                    }
                }
                const data = "https://wiki.mbalib.com/wiki/" + req.query.name;
                axios.get(data)
                    .then(response => {
                        const html = response.data;
                        const $ = cheerio.load(html);
                        let divs = $('.main_content');
                        const imageUrls = [];
                        divs.each((index, element) => {
                            const imageUrl = $(element).find('img').attr('src');
                            imageUrls.push(imageUrl);
                        });
                        const $1 = cheerio.load(html);
                        divs = $1('.main_content');
                        const text = divs.text().trim();
                        const $2 = cheerio.load(html);
                        divs = $2('.external');
                        const text2 = divs.text().trim();

                        db.query("select * from universities where name = '" + req.query.name + "'", (err, results) => {
                            if (results.length == 0) {
                                res.send({
                                    status: 0,
                                    content: '没有此院校的信息'
                                })
                                return;
                            }
                            db.query("select * from favoriteuniversities where name = '" + req.query.name + "' and userAccount = '" + req.query.userAccount + "'", (err, results1) => {
                                db.query("select * from cities where name like '%" + results[0].city.slice(0, 2) + "%'", (err, results2) => {
                                    results[0]['cityLevel'] = results2[0].level;

                                    let res11 = undefined;

                                    if (schoolId == undefined) {

                                    } else {
                                        axios.get("https://static-data.gaokao.cn/www/2.0/school/" + schoolId + "/info.json").then(res1 => {
                                            res11 = res1.data.data;
                                            axios.get("https://static-data.gaokao.cn/www/2.0/school/" + schoolId + "/pc_special.json").then(res2 => {
                                                axios.get("https://static-data.gaokao.cn/www/2.0/school/" + schoolId + "/rank.json").then(res3 => {
                                                    axios.get("https://static-data.gaokao.cn/www/2.0/school/" + schoolId + "/pc_jobdetail.json").then(res4 => {
                                                        res.send({
                                                            status: 1,
                                                            summary: text,
                                                            logoPics: imageUrls,
                                                            homePage: text2,
                                                            results: results,
                                                            isFavorited: (results1.length == 0 ? false : true),
                                                            res1: res11,
                                                            professionals: res2.data.data,
                                                            ranking: res3.data.data,
                                                            job: res4.data.data
                                                        })
                                                    })
                                                })
                                            })
                                        })
                                    }

                                    // res.send({
                                    //     status:1,
                                    //     summary:text,
                                    //     logoPics:imageUrls,
                                    //     homePage:text2,
                                    //     results:results,
                                    //     isFavorited:(results1.length==0?false:true),
                                    //     res1:res11
                                    // })
                                })

                            })

                        })


                    })
                    .catch(error => {
                        console.error(`获取网页内容出错: ${error}`);
                    });
            })
            .catch(error => {
                // 处理错误
                console.error(error);
            });

    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majors/deleteSelected', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        const total = data.length;
        let count = 0;
        for (let i = 0; i < data.length; i++) {
            db.query("delete from majors where majorCode = '" + data[i].slice(4, 6) + "' and universityCode = '" + data[i].slice(0, 4) + "'", (err, results) => {
                count += 1;
                if (count == total) {
                    res.send({
                        status: 1,
                        content: '删除成功'
                    })
                }
            })
        }
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

function getTheMajorContentsTable() {
    return new Promise((resolve, reject) => {
        db.query("select * from majorcontents", (err, results) => {

            return resolve(results)
        })
    })
}

let majorContents = []

function isInclude(arr, item) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == item) {
            return true
        }
    }
    return false
}

function doesItIncludeEnglishLettersAndSymbols(str) {
    let items = ['、', '(', ')', '（', '）', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '，']
    for (let i = 0; i < items.length; i++) {
        if (isSubstring(items[i], str) == true) {
            return true
        }
    }
    return false
}

function whetherItIsAMaskWord(str) {
    for (let i = 0; i < tagMaskWord.length; i++) {
        if (tagMaskWord[i] == str) {
            return true
        }
    }
    return false
}

function getSubstringByRules(str, rules) {
    let re = []
    for (let i = 0; i < rules.length; i++) {
        let count = 0
        let rightIndex = 0
        let currentLength = 0
        while (true) {
            rightIndex = rules[i][currentLength] + count
            if (rightIndex > str.length) {
                rightIndex = str.length
                if (count == rightIndex) {
                    break
                }
                if (isInclude(re, str.slice(count, rightIndex)) == false && doesItIncludeEnglishLettersAndSymbols(str.slice(count, rightIndex)) == false && str.slice(count, rightIndex).length != 1 && whetherItIsAMaskWord(str.slice(count, rightIndex)) == false) {
                    re.push(str.slice(count, rightIndex))
                }
                break
            }
            if (isInclude(re, str.slice(count, rightIndex)) == false && doesItIncludeEnglishLettersAndSymbols(str.slice(count, rightIndex)) == false && str.slice(count, rightIndex).length != 1 && whetherItIsAMaskWord(str.slice(count, rightIndex)) == false) {
                re.push(str.slice(count, rightIndex))
            }
            count += rules[i][currentLength]
            currentLength += 1
            if (currentLength > rules[i].length - 1) {
                currentLength = 0
            }
        }
    }
    return re
}

function getsTheNameOutsideTheParentheses(str) {
    for (let i = 0; i < str.length; i++) {
        if (str.slice(i, i + 1) == '(' || str.slice(i, i + 1) == '（') {
            return str.slice(0, i + 1)
        }
    }
    return str
}

function getTheSubjectLabel(volunteerItem) {
    let classTags = [volunteerItem.majorName]
    for (let i = 0; i < majorContents.length; i++) {
        if (isSubstring(majorContents[i].majorName, volunteerItem.majorName) == true && isInclude(classTags, majorContents[i].class) == false) {
            classTags.push(majorContents[i].class)
        }
    }
    let re = []
    let subjectItems = [yuwen, shuxue, waiyu, wuli, huaxue, shengwu, zhengzhi, lishi, dili]
    let rules = [
        [2],
        [3],
        [2, 3],
        [3, 2],
        [1, 2],
        [2, 1]
    ]
    let tags = getSubstringByRules(getsTheNameOutsideTheParentheses(volunteerItem.majorName), rules)
    for (let i = 0; i < 9; i++) {
        for (let i1 = 0; i1 < subjectItems[i].length; i1++) {
            for (let i2 = 0; i2 < tags.length; i2++) {
                if (isSubstring(tags[i2], subjectItems[i][i1]) == true) {
                    let subName = ''
                    switch (i) {
                        case 0:
                            subName = "语文"
                            break;
                        case 1:
                            subName = "数学"
                            break;
                        case 2:
                            subName = "外语"
                            break;
                        case 3:
                            subName = "物理"
                            break;
                        case 4:
                            subName = "化学"
                            break;
                        case 5:
                            subName = "生物"
                            break;
                        case 6:
                            subName = "政治"
                            break;
                        case 7:
                            subName = "历史"
                            break;
                        case 8:
                            subName = "地理"
                            break;
                    }
                    if (isInclude(re, subName) == false) {
                        re.push(subName.toString())
                    }
                }
            }
        }
    }

    return re

}


app.post('/api/v1/majors/importInfos', (req, res, next) => {

    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            // let formData = decodeURIComponent(data)   // 转码
            try {
                const predata = JSON.parse(formData)

                const total = predata.length;
                let count = 0;
                for (let i = 0; i < predata.length; i++) {

                    db.query("insert into majors values('" + (predata[i].majorCode == undefined ? '' : predata[i].majorCode) + "','" + (predata[i].majorName == undefined ? '' : predata[i].majorName) + "','" + (predata[i].universityCode == undefined ? '' : predata[i].universityCode) + "',  '" + (predata[i].universityName == undefined ? '' : predata[i].universityName) + "'," + (predata[i].ranking1 == undefined ? '0' : predata[i].ranking1) + "," + (predata[i].score1 == undefined ? '0' : predata[i].score1) + "," + (predata[i].num1 == undefined ? '0' : predata[i].num1) + "," + (predata[i].ranking2 == undefined ? '0' : predata[i].ranking2) + "," + (predata[i].score2 == undefined ? '0' : predata[i].score2) + "," + (predata[i].num2 == undefined ? '0' : predata[i].num2) + "," + (predata[i].ranking3 == undefined ? '0' : predata[i].ranking3) + "," + ((predata[i].score3 == undefined || predata[i].score3 == '') ? '0' : predata[i].score3) + "," + (predata[i].num3 == undefined ? '0' : predata[i].num3) + ",'" + (predata[i].province == undefined ? '' : predata[i].province) + "','" + (predata[i].city == undefined ? '' : predata[i].city) + "','" + (predata[i].subject == undefined ? '' : predata[i].subject) + "','" + (predata[i].money == undefined ? '' : predata[i].money) + "','" + (predata[i].level == undefined ? '' : predata[i].level) + "','" + (predata[i].batch == undefined ? '' : predata[i].batch) + "','" + (predata[i].detail == undefined ? '' : predata[i].detail) + "','" + getTheSubjectLabel(predata[i]) + "')", (err, results) => {
                        if (err) {
                        }
                        count += 1;
                        if (count == total) {
                            res.send({
                                status: 1,
                                content: '添加成功',
                            })
                        }
                    })
                }
                return;
            } catch (e) {
                res.send({
                    status: 2,
                    content: '重新发送'
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majors/import', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            let count = 1;
            while (true) {
                if (getStringByIndexAndChar(formData, count, ';') == undefined) {
                    count -= 1;
                    break;
                }
                count += 1;
            }


        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/universities/import', (req, res, next) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            if (isJSONString(formData)) {
                const predata = JSON.parse(formData)
                const total = predata.length;
                let count = 0;
                for (let i = 0; i < predata.length; i++) {
                    db.query("insert into universities values('" + predata[i]['名称'] + "','" + predata[i]['标识码'] + "','" + predata[i]['主管部门'] + "','" + predata[i]['所在省'] + "','" + predata[i]['所在市'] + "','" + predata[i]['办学层次'] + "','" + predata[i]['C9/985/211/省重点'] + "','" + predata[i]['一流大学/一流学科'] + "','" + predata[i]['院校类别'] + "','" + predata[i]['创办年数'] + "','" + predata[i]['创办时间'] + "','" + predata[i]['备注'] + "','" + predata[i]['第一轮双一流建设学科'] + "','" + predata[i]['第二轮双一流建设高校及建设学科'] + "',0,0)", (err, results) => {
                        count += 1;
                        if (count == total) {
                            res.send({
                                status: 1,
                                content: '添加成功',
                            })
                        }
                    })
                }
            } else {
                res.send({
                    status: 2,
                    content: '重新发送'
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/news/get', (req, res, next) => {
    try {
        axios.get('https://www.sdjyxww.com/gk?page=1')
            .then(response => {
                const html = response.data;

                // 使用cheerio加载HTML页面
                const $ = cheerio.load(html);

                // 找到类名为titlebox1的div元素
                const titlebox1 = $('.tabBox5-1');

                // 找到类名为titletxt1的div里的所有a标签
                const links = titlebox1.find('.pl0 a');

                // 遍历a标签，提取标题和地址，并整理成数组形式返回
                const result = [];
                links.each((index, element) => {
                    const title = $(element).attr('title');
                    const url = $(element).attr('href');
                    result.push({ title, url });
                });

                axios.get('https://www.sdjyxww.com/gk?page=2')
                    .then(response => {
                        const html = response.data;

                        // 使用cheerio加载HTML页面
                        const $ = cheerio.load(html);

                        // 找到类名为titlebox1的div元素
                        const titlebox1 = $('.tabBox5-1');

                        // 找到类名为titletxt1的div里的所有a标签
                        const links = titlebox1.find('.pl0 a');

                        // 遍历a标签，提取标题和地址，并整理成数组形式返回
                        links.each((index, element) => {
                            const title = $(element).attr('title');
                            const url = $(element).attr('href');
                            result.push({ title, url });
                        });

                        axios.get('https://www.sdjyxww.com/gk?page=3')
                            .then(response => {
                                const html = response.data;

                                // 使用cheerio加载HTML页面
                                const $ = cheerio.load(html);

                                // 找到类名为titlebox1的div元素
                                const titlebox1 = $('.tabBox5-1');

                                // 找到类名为titletxt1的div里的所有a标签
                                const links = titlebox1.find('.pl0 a');

                                // 遍历a标签，提取标题和地址，并整理成数组形式返回
                                links.each((index, element) => {
                                    const title = $(element).attr('title');
                                    const url = $(element).attr('href');
                                    result.push({ title, url });
                                });

                                res.send({
                                    status: 1,
                                    baseURL: 'https://www.sdjyxww.com/',
                                    results: result
                                })
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                res.send({
                                    status: 0,
                                    content: '获取失败'
                                })
                            });
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        res.send({
                            status: 0,
                            content: '获取失败'
                        })
                    });
            })
            .catch(error => {
                console.error('Error:', error);
                res.send({
                    status: 0,
                    content: '获取失败'
                })
            });
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/universities/update', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("update universities set name = '" + data.name + "', department = '" + data.department + "', province = '" + data.province + "', city = '" + data.city + "', level = '" + data.level + "', focus = '" + data.focus + "', firstRate = '" + data.firstRate + "', type = '" + data.type + "', year = '" + data.year + "', yearCount = '" + data.yearCount + "', public = '" + data.public + "', subject1 = '" + data.subject1 + "', subject2 = '" + data.subject2 + "' where remark = '" + data.remark + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败',
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/universities/deleteSelected', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        const total = data.length;
        let count = 0;
        for (let i = 0; i < data.length; i++) {
            db.query("delete from universities where remark = '" + data[i] + "'", (err, results) => {
                count += 1;
                if (count == total) {
                    res.send({
                        status: 1,
                        content: '删除成功'
                    })
                }
            })
        }
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/universities/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into universities values('" + data.name + "','" + data.remark + "','" + data.department + "','" + data.province + "','" + data.city + "','" + data.level + "','" + data.focus + "','" + data.firstRate + "','" + data.type + "','" + data.year + "','" + data.yearCount + "','" + data.public + "','" + data.subject1 + "','" + data.subject2 + "',0,0)", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '添加失败',
                })
            } else {
                res.send({
                    status: 1,
                    content: '添加成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/universities/search', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from universities where name like '%" + data.name + "%' and remark like '%" + data.remark + "%' and province like '%" + data.province + "%' and city like '%" + data.city + "%' order by minScore DESC", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majors/update', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("update majors set majorCode = '" + data.majorCode + "', universityCode = '" + data.universityCode + "', ranking1 = " + data.ranking1 + ", score1 = " + data.score1 + ", num1 = " + data.num1 + ", ranking2 = " + data.ranking2 + ", score2 = " + data.score2 + ", num2 = " + data.num2 + ", ranking3 = " + data.ranking3 + ", score3 = " + data.score3 + ", num3 = " + data.num3 + ", province = '" + data.province + "', city = '" + data.city + "', subject = '" + data.subject + "', money ='" + data.money + "', level = '" + data.level + "', batch = '" + data.batch + "' where universityName = '" + data.universityName + "' and majorName = '" + data.majorName + "'", (err, result) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/majors/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("insert into majors values('" + data.majorCode + "','" + data.majorName + "','" + data.universityCode + "','" + data.universityName + "'," + data.ranking1 + "," + data.score1 + "," + data.num1 + "," + data.ranking2 + "," + data.score2 + "," + data.num2 + "," + data.ranking3 + "," + data.score3 + "," + data.num3 + ",'" + data.province + "','" + data.city + "','" + data.subject + "','" + data.money + "','" + data.level + "','" + data.batch + "')", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '添加失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '添加成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/users/delete', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("delete from users where account = '" + data.account + "'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '删除失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '删除成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/users/search', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users where name like '%" + data.name + "%' and idNumber like '%" + data.idNumber + "%' and account like '%" + data.account + "%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/users/improve', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        console.log(data.subjectScores)
        db.query("update users set name = '" + data.name + "',idNumber = '" + data.idNumber + "',score = '" + data.score + "',ranking = '" + data.ranking + "',province = '" + data.province + "',subjects = '" + data.subjects + "',isSM = " + data.isSM + ",isSR = " + data.isSR + " ,scoresOfEachSubject = '" + data.subjectScores + "' where account = '" + data.account + "'", (err, results) => {

            if (err) {
                res.send({
                    status: 0,
                    content: '修改失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '修改成功'
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.get('/api/v1/majors/search', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from majors where majorCode like '%" + data.majorCode + "%' and majorName like '%" + data.majorName + "%' and universityCode like '%" + data.universityCode + "%' and universityName like '%" + data.universityName + "%'", (err, results) => {
            if (err) {
                res.send({
                    status: 0,
                    content: '查询失败'
                })
            } else {
                res.send({
                    status: 1,
                    content: '查询成功',
                    results: results
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/users/add', (req, res, next) => {
    try {
        const data = JSON.parse(req.query.data);
        db.query("select * from users", (err, results) => {
            if (err) {
                res1 = {
                    status: -1,
                    content: '请求失败',
                }
                res.send(JSON.stringify(res1))
            } else {
                var date = new Date();
                db.query("select * from users", (err, results) => {
                    if (err) {
                        res1 = {
                            status: -2,
                            content: '请求失败',
                        }
                        res.send(JSON.stringify(res1))
                    } else {
                        let re = [];
                        for (let i = 0; i < results.length; i++) {
                            if (results[i].account.slice(0, 2) == date.getFullYear().toString().slice(2, 4)) {
                                re.push(results[i]);
                            }
                        }
                        let account = '';
                        if (re.length == 0) {
                            account = date.getFullYear().toString().slice(2, 4) + '00000001';
                        } else {
                            account = convertAndIncrement(re[re.length - 1].account);
                        }

                        db.query("insert into users values('" + account + "','" + data.password + "','" + data.name + "','" + '' + "','" + '' + "'," + '0' + ",'" + '' + "','" + data.idNumber + "',2,'-',0,0,'')", (err, results) => {
                            if (err) {
                                res1 = {
                                    status: -3,
                                    content: '请求失败',
                                }
                                res.send(JSON.stringify(res1))
                            } else {
                                res.send({
                                    status: 0,
                                    content: '添加成功',
                                    account: account,
                                })
                            }
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/scoreranking/import', (req, res) => {
    try {
        req.on('data', data => {
            // 获取并解析post提交过来的数据
            let formData = decodeURIComponent(data)   // 转码
            const predata = JSON.parse(formData)
            const total = predata.data.length
            let count = 0
            for (let i = 0; i < total; i++) {
                db.query("insert into scoreranking values(" + predata.data[i]['分数'] + "," + predata.data[i]['位次'] + "," + predata.year + ")", (err, results) => {
                    count += 1
                    if (count == total) {
                        res.send({
                            status: 1,
                            content: '导入成功'
                        })
                    }
                })
            }

        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.post('/api/v1/scoreranking/deleteAll', (req, res) => {
    db.query("delete from scoreranking", (err, results) => {
        res.send({
            status: 1,
            content: "清空成功"
        })
    })
})

app.get('/api/v1/scoreranking/search', (req, res) => {
    const data = JSON.parse(req.query.data)
    db.query("select * from scoreranking where year = '" + data.year + "'", (err, results) => {
        if (err) {
            res.send({
                status: 0,
                content: '获取失败'
            })
        } else {
            res.send({
                status: 1,
                content: '获取成功',
                results: results
            })
        }
    })
})

app.get('/api/v1/users/regist', (req, res, next) => {
    try {
        var data = JSON.parse(req.query.data);
        db.query("select * from users", (err, results) => {
            if (err) {
                res1 = {
                    status: -1,
                    content: '请求失败',
                }
                res.send(JSON.stringify(res1))
            } else {
                var date = new Date();
                db.query("select * from users", (err, results) => {
                    if (err) {
                        res1 = {
                            status: -2,
                            content: '请求失败',
                        }
                        res.send(JSON.stringify(res1))
                    } else {
                        let re = [];
                        for (let i = 0; i < results.length; i++) {
                            if (results[i].account.slice(0, 2) == date.getFullYear().toString().slice(2, 4)) {
                                re.push(results[i]);
                            }
                        }
                        let account = '';
                        if (re.length == 0) {
                            account = date.getFullYear().toString().slice(2, 4) + '00000001';
                        } else {
                            account = convertAndIncrement(re[re.length - 1].account);
                        }
                        const teacherAccount = getTeacherAccount();
                        db.query("select * from users where userType = 2", (err, results) => {
                            if (results.length == 0) {
                                db.query("insert into users values('" + account + "','" + data.password + "','" + data.name + "','" + data.home + "','" + data.subjects + "'," + data.score + ",'" + data.ranking + "','" + data.idNumber + "',1,'',0,0,'')", (err, results) => {
                                    if (err) {
                                        res1 = {
                                            status: -3,
                                            content: '请求失败',
                                        }
                                        res.send(JSON.stringify(res1))
                                    } else {
                                        res.send({
                                            status: 0,
                                            content: '添加成功',
                                            account: account,
                                        })
                                    }
                                })
                                return;
                            }
                            let total = results.length;
                            let count = 0;
                            let min = {
                                account: undefined,
                                num: 99999999,
                            }
                            for (let i = 0; i < results.length; i++) {
                                db.query("select * from users where account = '" + results[i].teacherAccount + "'", (err, results1) => {
                                    if (results1.length < min.num) {
                                        min.num = results1.length;
                                        min.account = results[i].account;
                                        count += 1;
                                        if (count == total) {
                                            db.query("insert into users values('" + account + "','" + data.password + "','" + data.name + "','" + data.home + "','" + data.subjects + "'," + data.score + ",'" + data.ranking + "','" + data.idNumber + "',1,'" + min.account + "',0,0,'')", (err, results) => {
                                                if (err) {
                                                    res1 = {
                                                        status: -3,
                                                        content: '请求失败',
                                                    }
                                                    res.send(JSON.stringify(res1))
                                                } else {
                                                    res.send({
                                                        status: 0,
                                                        content: '添加成功',
                                                        account: account,
                                                    })
                                                }
                                            })
                                            return;
                                        }
                                    }
                                })
                            }
                        })
                    }
                })
            }
        })
    } catch (err) {
        // 将错误传递给错误处理中间件
        next(err);
    }
})

app.use((err, req, res, next) => {
    // 处理错误逻辑
    res.send({
        status: -1,
        msg: "遇到了一个错误"
    })
});

app.listen(port, async () => {
    majorContents = await getTheMajorContentsTable()
    db.query("select account from users", (err, results) => {
        for (let i = 0; i < results.length; i++) {
            userStatus.push({
                account: results[i].account,
                status: 0,
                unreadNum: 0
            })
        }
    })
    db.query("select * from systemsettings", (err, results) => {
        checkItems = ['batchScore'];
        checkItemsExplain = ['1段、2段分数线'];
        checkItemsValues = [JSON.stringify({
            batch1: 0,
            batch2: 0
        })]
        for (let i = 0; i < checkItems.length; i++) {
            let flag = true;
            for (let i1 = 0; i1 < results.length; i1++) {
                if (results[i1].keyName == checkItems[i]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                db.query("insert into systemsettings values('" + checkItems[i] + "','" + checkItemsValues[i] + "','" + checkItemsExplain[i] + "')");
            }
        }
    })
    setInterval(() => {
        for (let i = 0; i < userStatus.length; i++) {
            userStatus[i].status = 0;
        }
    }, 30000)
})


function isJSONString(str) {
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
}

function parseDateTime(dateTimeStr) {
    const year = '20' + dateTimeStr.slice(0, 2);
    const month = parseInt(dateTimeStr.slice(2, 4)) - 1;
    const day = dateTimeStr.slice(4, 6);
    const hour = dateTimeStr.slice(6, 8);
    const minute = dateTimeStr.slice(8, 10);

    const date = new Date(year, month, day, hour, minute);
    return date;
}

function isSubstring(shortStr, longStr) {
    return longStr.indexOf(shortStr) !== -1;
}

function convertStringToArray(str) {
    // 使用逗号作为分隔符将字符串分割为数组
    var arr = str.split(',');

    // 使用map方法对数组中的每个元素进行处理，去除首尾的空格
    arr = arr.map(function (item) {
        return item.trim();
    });

    return arr;
}

function subtractYear(num) {
    var currentYear = new Date().getFullYear();
    return currentYear - num;
}

function calculateAdmissionProbability(scores, ranks, admissionsData, studentScore, studentRank) {
    let totalAdmissions = 0;
    let studentAdmissions = 0;

    // 遍历 admissionsData 数组，获取每年的位次、分数线和录取人数
    for (let i = 0; i < admissionsData.length; i++) {
        let rankData = ranks[i];
        let scoreData = scores[i];
        let admissionsCount = admissionsData[i];

        // 判断考生的位次是否在录取位次范围内
        if (studentRank <= rankData) {
            totalAdmissions += admissionsCount;

            // 判断考生的分数是否达到录取分数线
            if (studentScore >= scoreData) {
                studentAdmissions += admissionsCount;
            }
        }
    }

    // 计算考生被录取的概率
    let admissionProbability = studentAdmissions / totalAdmissions;
    return admissionProbability;
}

function getTeacherAccount() {
    db.query("select * from users where userType = 2", (err, results) => {
        if (results.length == 0) {
            return '';
        }
        let total = results.length;
        let count = 0;
        let min = {
            account: undefined,
            num: 99999999,
        }
        for (let i = 0; i < results.length; i++) {
            db.query("select * from users where account = '" + results[i].teacherAccount + "'", (err, results1) => {
                if (results1.length < min.num) {
                    min.num = results1.length;
                    min.account = results[i].account;
                    count += 1;
                    if (count == total) {
                        return min.account;
                    }
                }
            })
        }
    })
}

function convertAndIncrement(str) {
    // 将字符串转换成10位数字
    let num = parseInt(str, 10);

    // 加1
    num++;

    // 将加1后的数字转换成10位字符串
    let result = String(num).padStart(10, '0');

    return result;
}

function getAccount(number) {
    const year = new Date().getFullYear().toString().slice(-2);
    const paddedNumber = number.toString().padStart(9 - number.toString().length, '0');
    const formattedString = year + paddedNumber;
    return formattedString;
}

function checkUserKey(account, key) {
    for (let i = 0; i < keys.length; i++) {
        if (keys[i].account == account && keys[i].key == key) {
            return true;
        }
    }
    return false;
}

function storeOrRefreshAccessKey(arr, account, key) {
    let flag = true;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].account == account) {
            arr[i].key = key;
            flag = false;
            break;
        }
    }
    if (flag) {
        arr.push({
            data: account.account,
            key: key
        })
    }
    return arr;
}
function generateTimeString() {
    var currentDate = new Date();

    var year = currentDate.getFullYear();
    var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
    var day = ('0' + currentDate.getDate()).slice(-2);
    var hours = ('0' + currentDate.getHours()).slice(-2);
    var minutes = ('0' + currentDate.getMinutes()).slice(-2);
    var seconds = ('0' + currentDate.getSeconds()).slice(-2);

    var formattedTime = year + month + day + hours + minutes + seconds;
    return formattedTime;
}

function generateAccessKey() {
    return sha256(formatCurrentTime());
}

function formatCurrentTime() {
    const currentDate = new Date();
    const year = currentDate.getFullYear().toString().padStart(4, '0');
    const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
    const day = currentDate.getDate().toString().padStart(2, '0');
    const hours = currentDate.getHours().toString().padStart(2, '0');
    const minutes = currentDate.getMinutes().toString().padStart(2, '0');
    const seconds = currentDate.getSeconds().toString().padStart(2, '0');

    return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

function sha256(input) {
    const hash = crypto.createHash('sha256');
    hash.update(input);
    return hash.digest('hex');
}

function subjectResolve(subs) {
    const res = [];
    res.push("'不限'", `'${subjects[subs[0]]}和${subjects[subs[1]]}'`, `'${subjects[subs[0]]}和${subjects[subs[2]]}'`, `'${subjects[subs[1]]}和${subjects[subs[2]]}'`)
    return res
}
function subjectResolve2(subs) {
    return `'${subjects[subs[0]]}','${subjects[subs[1]]}','${subjects[subs[2]]}'` // '物理','化学','生物'
}

//////////////////////////////////////////////////////////////
function conditionSql(searchForm) {
    let addSql = `batch='${searchForm.batch}'`;

    if (searchForm.universityName != '') addSql += ` and universityName like '%${searchForm.universityName}%'`
    if (searchForm.moneyMax != '') addSql += ` and (money='待定' or cast(money as signed)<=${searchForm.moneyMax})`

    let levels = []
    if (searchForm.levels.length != 0) {
        searchForm.levels.forEach((el) => {
            levels.push(`level like '%${el}%'`)
        })
        addSql += ` and (${levels.join(' or ')})`
    }

    if (searchForm.provinces.length != 0) {
        let provinces = ""
        searchForm.provinces.forEach((el, index) => {
            provinces += `${index !== 0 ? ',' : ''}'${el}'`
        })
        addSql += ` and province in (${provinces})`
    }

    let majorNames = []
    searchForm.majorName.forEach((el, i) => {
        majorNames.push(`majorName like '%${el}%'`)
    })
    if (majorNames.length != 0) {
        addSql += ` and (${majorNames.join(' or ')})`
    }

    return addSql

}



async function lineDifMethod(form, addSql) {

    const res = await getAll(form.score + form.scoreUp, form.score - form.scoreDown, false, addSql, form.page);
    const aplications = res.res
    form.count = res.count

    return aplications
}

// 位次法
async function rankMethod(form, addSql) {


    // 获取冲的最前排名
    form.frontRank = await selectRankByYearScore(form.year, form.score + form.scoreUp);

    // 获取保的最低排名
    form.backRank = await selectRankByYearScore(form.year, form.score - form.scoreDown);

    const res = await getAll(form.frontRank, form.backRank, true, addSql, form.page);

    const aplications = res.res
    form.count = res.count


    return aplications

}
// 冲稳保全在
function getAll(front_up, back_down, rankMethod, addSql, page = -1) {
    return new Promise((resolve, rejects) => {
        const pageLimitSql = getPageLimitSql(page);

        // 选出后需要以位次排名 有序返回
        if (rankMethod) {
            db.query(`select * from majors where ${addSql} and ranking3>=? and ranking3<=? ${pageLimitSql}`, [front_up, back_down], (err, res) => {
                db.query(`select count(*) count from majors where ${addSql} and ranking3>=? and ranking3<=? ${pageLimitSql}`, [front_up, back_down], (err, res2) => {
                    if (err) return rejects(err)
                    return resolve({
                        res: res,
                        count: count
                    })
                })

            })
            //按照分数
        } else db.query(`select * from majors where ${addSql} and score3>=? and score3<=? ${pageLimitSql}`, [back_down, front_up], (err, res) => {
            if (err) return rejects(err)
            db.query(`select count(*) count from majors where ${addSql} and score3>=? and score3<=?`, [back_down, front_up], (err, res) => {
                return resolve({
                    res: res,
                    count: count
                })

            })
        });
    })

}

function getPageLimitSql(page) {
    let pageLimitSql = ''
    if (page != -1) {
        pageLimitSql = `limit 30${page ? " offset " + page * 30 : ""}` // limit 10 offset 30
    }
    return pageLimitSql;
}

function selectRankByYearScore(year, score) {
    return new Promise((resolve, rejects) => {
        db.query("select score,ranking from scoreranking where year=? order by ranking asc", [year], (err, res) => {
            if (err) return rejects(err);
            const rows = res

            for (let i = 0; i < rows.length; i++) {
                if (score >= rows[i].score) {
                    return resolve(rows[i].ranking)
                }
            }
        })
    })


}


methods = {
    conditionSql: conditionSql,
    rankMethod: rankMethod,
    lineDifMethod: lineDifMethod,
    getAll: getAll,
    selectRankByYearScore: selectRankByYearScore

}